Twitter (X) API in Golang: a typed net/http client with iterators and rate limiting

By TwitterAPI.io Team•13 min read
Diagram mapping TwitterAPI.io JSON fields to Go types: id to string, createdAt to time.RubyDate, retweeted_tweet and quoted_tweet to *Tweet, extendedEntities to a value struct, place to json.RawMessage, and has_next_page with next_cursor to an iter.Seq2 iterator, each with its measured count from 1,402 tweets.
The JSON-to-Go type map this guide builds, measured on 1,402 real tweets collected in 2026.
TL;DR
  • Standard library first: net/http, encoding/json, context and iter cover the whole client; the only optional dependency is golang.org/x/time/rate for a shared limiter.
  • Types from data, not guesses: 1,129 of 1,402 tweets had retweeted_tweet: null and 1,357 had quoted_tweet: null, so both are *Tweet; extendedEntities was {} (never null) on 752 tweets, so it stays a value type.
  • Ids are strings, dates are RubyDate: all 1,402 ids were 19-digit JSON strings and every createdAt parsed with Go's built-in time.RubyDate layout.
  • Plan for slow first pages: the first page of a timeline took a median 5.8 s and later cursor pages 2.2 s; a 30-second http.Client.Timeout leaves room for the 7.6 s maximum.
  • Short pages are normal: 30 of 75 pages held fewer than 20 tweets while has_next_page was still true, so the iterator loops on the flag, never on len(tweets).
  • Cost: $0.15 per 1,000 tweets returned on TwitterAPI.io versus $0.005 per post read ($5 per 1,000) on X's pay-per-usage rate card, about 33x.

Search for a Twitter API Golang example and you land on library repositories written for X's own API: OAuth 1.0a signing, bearer tokens, a developer app, and in several cases code that targets the v1.1 endpoints that X retired years ago. None of them show what a tweet looks like when Go's encoding/json meets it, which is where Go code actually breaks: a null object decoded into a value type you then trust, an empty {} that a nil check never catches, a pagination loop that stops on a short page, or a request that hangs because http.DefaultClient has no timeout.

This guide builds a small Go client for TwitterAPI.io with the standard library only: one http.Client, typed structs, a retrying Get with readable error types, iter.Seq2 iterators for cursor pages, context.Context cancellation, and a worker pool that shares one rate limiter. Every type choice comes from 1,402 real tweets we pulled from 14 Go-ecosystem organization accounts, including @golang, @kubernetesio, @PrometheusIO, @grafana and @HashiCorp. The Go code was compiled, vetted and run against the live API with Go 1.27.4, and a test decoded every sampled page into these structs.

Decode errors when 1,402 real tweets were unmarshaled into this page's Go structs

0

01 — Section

Go Twitter libraries in 2026: what still works and what they target

The phrase "Twitter API Golang" covers two different services. X's official API lives at api.x.com under /2/... paths, needs a developer account and an app, authenticates with OAuth 2.0 bearer tokens or OAuth 1.0a user context, and bills on X's pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing). TwitterAPI.io is a separate service at api.twitterapi.io with paths such as /twitter/user/last_tweets; reads use one key in an X-API-Key header and no X account is needed.

Every community Go library we checked targets the first one. We read their GitHub repositories this session:

LibraryTargetsStatus we found
dghubble/go-twitterX API v1.1 (OAuth)archived; README marked DEPRECATED, no longer developed since November 2022
g8rswimmer/go-twitter/v2X API v2 (OAuth)not archived; last commit December 2022, latest release v2.1.5
michimani/gotwiX API v2 (OAuth 1.0a, OAuth 2.0 bearer)active; release v0.18.5 and commits in 2026; README says still under development

When a library is the right call. If you hold X developer credentials and need user-context OAuth against X's own endpoints, gotwi is the maintained option of the three. It does not speak to TwitterAPI.io, and its examples assume X's tiers and prices.

Why no library here. Against TwitterAPI.io the protocol is HTTPS plus JSON with one header, so the client below is about 150 lines of standard-library Go. Owning it means owning the struct tags, which is exactly what the measurements in the next section are for.

02 — Section

Typed structs that match the JSON you actually get

Go makes you choose, for every field, between a value and a pointer, and between a concrete struct and json.RawMessage. We let the data choose. Across 1,402 tweets, each field arrived in one of four states: with content, null, an empty {} or [], or missing entirely. The chart below shows the split.

Fieldnull{} or []has contentGo type here
retweeted_tweet1,1290273*Tweet
quoted_tweet1,357045*Tweet
card1,0440358json.RawMessage
extendedEntities0752650value struct
place01,3966json.RawMessage
inReplyToId1,40200*string

Null means pointer. retweeted_tweet and quoted_tweet are null unless the tweet is a repost or a quote, so *Tweet gives you a clean if tw.RetweetedTweet != nil test. A value type would decode null into a zero Tweet and you would have to guess from an empty ID. In our sample 19.5% of tweets were reposts; their text is the repost form, and the original sits under retweeted_tweet.

Empty object means value. extendedEntities never came back null: it was {} on 752 tweets and carried media on 650 (46.4%). A pointer would be non-nil in both cases and tell you nothing, so keep it a value type and test len(tw.ExtendedEntities.Media) > 0. place was {} on 1,396 of 1,402 tweets; it stays json.RawMessage until you need it.

Missing and null look the same to Go. communityInfo was null on 1,222 tweets and missing on 180; encoding/json leaves a pointer nil in both cases, which is what you want. If you ever need to tell them apart, decode into a map[string]json.RawMessage first.

Ids, counters and dates. Every tweet id, conversationId and author.id was a JSON string of 19 digits, above 2^53, so use string and never float64 (and do not add a ,string tag option; the value is already a string). The largest counters we saw, 4,541,221 views and 22,562 likes, fit any Go int. viewCount was 0 on 135 tweets (55 of them reposts), so treat 0 as "no count" rather than proof that nobody saw a post. createdAt (Thu Oct 16 12:34:56 +0000 2026) is exactly Go's predefined time.RubyDate layout, so a three-line UnmarshalJSON turns it into a time.Time.

go
package twitterapi

import (
	"encoding/json"
	"time"
)

// Tweet mirrors the fields of a tweet object. Ids are strings: all 1,402 ids in
// our sample were 19-digit JSON strings. Objects that came back as null in our
// sample are pointers; objects that came back as {} are values.
type Tweet struct {
	ID             string   `json:"id"`
	URL            string   `json:"url"`
	Text           string   `json:"text"`
	CreatedAt      RubyTime `json:"createdAt"`
	Lang           string   `json:"lang"`
	ConversationID string   `json:"conversationId"`

	LikeCount     int `json:"likeCount"`
	RetweetCount  int `json:"retweetCount"`
	ReplyCount    int `json:"replyCount"`
	QuoteCount    int `json:"quoteCount"`
	ViewCount     int `json:"viewCount"` // 0 can mean "no count", not only "nobody saw it"
	BookmarkCount int `json:"bookmarkCount"`

	IsReply           bool    `json:"isReply"`
	InReplyToID       *string `json:"inReplyToId"`       // null unless it is a reply
	InReplyToUsername *string `json:"inReplyToUsername"` // null unless it is a reply

	Author           User             `json:"author"`
	Entities         Entities         `json:"entities"`
	ExtendedEntities ExtendedEntities `json:"extendedEntities"` // {} when there is no media
	Place            json.RawMessage  `json:"place"`            // {} on 99.6% of our sample
	Card             json.RawMessage  `json:"card"`             // null or a card object
	QuotedTweet      *Tweet           `json:"quoted_tweet"`     // null unless a quote
	RetweetedTweet   *Tweet           `json:"retweeted_tweet"`  // null unless a repost
}

type User struct {
	ID             string `json:"id"`
	UserName       string `json:"userName"`
	Name           string `json:"name"`
	Description    string `json:"description"`
	Location       string `json:"location"`
	Followers      int    `json:"followers"`
	Following      int    `json:"following"`
	StatusesCount  int    `json:"statusesCount"`
	IsBlueVerified bool   `json:"isBlueVerified"`
	IsVerified     bool   `json:"isVerified"`
	IsAutomated    bool   `json:"isAutomated"`
	Protected      bool   `json:"protected"`
	CreatedAt      string `json:"createdAt"`
}

type Entities struct {
	Hashtags []struct {
		Text string `json:"text"`
	} `json:"hashtags"`
	URLs []struct {
		URL         string `json:"url"`
		ExpandedURL string `json:"expanded_url"`
	} `json:"urls"`
	UserMentions []struct {
		ScreenName string `json:"screen_name"`
	} `json:"user_mentions"`
}

type ExtendedEntities struct {
	Media []struct {
		Type          string `json:"type"` // photo, video or animated_gif
		MediaURLHTTPS string `json:"media_url_https"`
	} `json:"media"`
}

// RubyTime parses createdAt ("Thu Oct 16 12:34:56 +0000 2026"), which is
// exactly Go's time.RubyDate layout.
type RubyTime struct{ time.Time }

func (t *RubyTime) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	if s == "" {
		return nil
	}
	parsed, err := time.Parse(time.RubyDate, s)
	if err != nil {
		return err
	}
	t.Time = parsed
	return nil
}

// Response shapes: last_tweets nests tweets under data, advanced_search does not.
type lastTweetsResponse struct {
	Data struct {
		Tweets []Tweet `json:"tweets"`
	} `json:"data"`
	HasNextPage bool   `json:"has_next_page"`
	NextCursor  string `json:"next_cursor"`
}

type searchResponse struct {
	Tweets      []Tweet `json:"tweets"`
	HasNextPage bool    `json:"has_next_page"`
	NextCursor  string  `json:"next_cursor"`
}

type userInfoResponse struct {
	Data *User `json:"data"`
}
Stacked bar chart of 1,402 tweets: retweeted_tweet null on 80.5%, quoted_tweet null on 96.8%, card null on 74.5%, extendedEntities empty object on 53.6%, place empty object on 99.6%, viewCount present on 100%, inReplyToId null on 100%.
How each tweet field arrived in JSON across 1,402 tweets from 14 Go-ecosystem organization accounts, collected in 2026.
03 — Section

One http.Client and a Get method with retries and error types

http.DefaultClient has no timeout, so a stalled connection can block a goroutine indefinitely. Create one http.Client with Timeout set and reuse it for the life of the process: its Transport keeps TLS connections alive between calls. The Go documentation notes that Timeout covers connecting, redirects and reading the body, and that the client cancels the request as if its context ended.

How long to wait. In our collection the first page of each timeline (no cursor) took a median 5.8 s and never less than 4.1 s, while later pages fetched with a cursor took a median 2.2 s; the slowest page took 7.6 s. A 10-second timeout would sit close to that edge, so the client uses 30 seconds and lets the caller's context impose a tighter deadline when it needs one.

What to retry. Retry HTTP 429, 502, 503 and 504 with exponential backoff and jitter, and honor Retry-After when present. During collection 2 of our page requests still failed after five attempts while the service was answering 503, which is why the retry loop is not optional and why the final error wraps the last cause with %w.

Two kinds of error body. A missing or invalid parameter returns HTTP 400 with the text in detail; we sent /twitter/tweet/advanced_search without a query and got query is required. An unknown account on /twitter/user/info is different: HTTP 200 with status: "error", msg: "user not found" and data: null. The client turns both into an *APIError, so callers use errors.As and never mistake an error body for an empty result.

Bound the body. A 20-tweet page was a median 98 KB and up to 186 KB of JSON (re-serialized, about 5,540 bytes per tweet), so io.LimitReader at 8 MB is generous while still protecting a service from a runaway response.

go
// Package twitterapi is a small standard-library client for TwitterAPI.io reads.
package twitterapi

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math/rand/v2"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

const baseURL = "https://api.twitterapi.io"

// Client holds one shared *http.Client. Create it once and reuse it: the
// Transport keeps TLS connections alive between calls.
type Client struct {
	key         string
	http        *http.Client
	MaxAttempts int
	// Limiter, when set, is waited on before every attempt. *rate.Limiter from
	// golang.org/x/time/rate satisfies it; the client itself stays stdlib-only.
	Limiter interface{ Wait(context.Context) error }
}

func New(apiKey string) *Client {
	return &Client{
		key: apiKey,
		// Timeout covers connect, redirects and reading the body. First pages of a
		// timeline took up to about 7.6 s in our sample, so leave headroom.
		http:        &http.Client{Timeout: 30 * time.Second},
		MaxAttempts: 4,
	}
}

// APIError carries the HTTP status and the server's message.
type APIError struct {
	Status int    // HTTP status code (200 when the body said status "error")
	Msg    string // "msg" on errors, "detail" on HTTP 400
	Path   string
}

func (e *APIError) Error() string {
	return fmt.Sprintf("twitterapi: HTTP %d on %s: %s", e.Status, e.Path, e.Msg)
}

// envelope is the part every response shares.
type envelope struct {
	Status string          `json:"status"`
	Msg    string          `json:"msg"`
	Detail json.RawMessage `json:"detail"`
}

func retryable(code int) bool {
	return code == http.StatusTooManyRequests || code == http.StatusBadGateway ||
		code == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout
}

func backoff(attempt int, h http.Header) time.Duration {
	if s, err := strconv.Atoi(h.Get("Retry-After")); err == nil && s > 0 {
		return min(time.Duration(s)*time.Second, time.Minute)
	}
	base := 500 * time.Millisecond << (attempt - 1) // 0.5 s, 1 s, 2 s ...
	return base + time.Duration(rand.Int64N(int64(250*time.Millisecond)))
}

func sleep(ctx context.Context, d time.Duration) error {
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

// Get sends GET path?query and decodes the JSON body into out.
func (c *Client) Get(ctx context.Context, path string, query url.Values, out any) error {
	u := baseURL + path
	if len(query) > 0 {
		u += "?" + query.Encode()
	}
	var lastErr error
	for attempt := 1; attempt <= c.MaxAttempts; attempt++ {
		if c.Limiter != nil {
			if err := c.Limiter.Wait(ctx); err != nil {
				return err
			}
		}
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
		if err != nil {
			return err
		}
		req.Header.Set("X-API-Key", c.key)
		req.Header.Set("Accept", "application/json")

		resp, err := c.http.Do(req)
		if err != nil { // DNS, TLS, timeout, or ctx cancelled
			if ctx.Err() != nil {
				return ctx.Err()
			}
			lastErr = err
			if err := sleep(ctx, backoff(attempt, nil)); err != nil {
				return err
			}
			continue
		}
		body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
		resp.Body.Close()
		if err != nil {
			lastErr = err
			continue
		}
		if retryable(resp.StatusCode) && attempt < c.MaxAttempts {
			lastErr = &APIError{Status: resp.StatusCode, Msg: http.StatusText(resp.StatusCode), Path: path}
			if err := sleep(ctx, backoff(attempt, resp.Header)); err != nil {
				return err
			}
			continue
		}
		var env envelope
		_ = json.Unmarshal(body, &env) // best effort: error bodies may not be JSON
		if resp.StatusCode != http.StatusOK {
			msg := env.Msg
			if len(env.Detail) > 0 { // HTTP 400: the text names the bad parameter
				var d string
				if json.Unmarshal(env.Detail, &d) != nil {
					d = string(env.Detail) // not a plain string: keep the raw JSON
				}
				msg = d
			}
			if msg == "" {
				msg = http.StatusText(resp.StatusCode)
			}
			return &APIError{Status: resp.StatusCode, Msg: msg, Path: path}
		}
		if env.Status == "error" { // HTTP 200 with status "error", e.g. user not found
			return &APIError{Status: http.StatusOK, Msg: env.Msg, Path: path}
		}
		return json.Unmarshal(body, out)
	}
	return fmt.Errorf("twitterapi: %s failed after %d attempts: %w", path, c.MaxAttempts, lastErr)
}

// IsNotFound reports whether err is the HTTP 200 "user not found" error.
func IsNotFound(err error) bool {
	var e *APIError
	return errors.As(err, &e) && e.Msg == "user not found"
}
Two bar charts. Left: median response time 5.8 s for first timeline pages, 2.2 s for cursor pages, p90 5.9 s, max 7.6 s. Right: page size min 58 KB, median 98 KB, p90 135 KB, max 186 KB.
Response time and JSON size of 75 /twitter/user/last_tweets pages, collected in 2026.
04 — Section

Cursor pagination as a Go 1.23 iterator (iter.Seq2)

Go 1.23 added range-over-func: a function of type iter.Seq2[K, V] (from the standard iter package) can be used directly in a for ... range loop. That is a natural fit for cursor paging. LastTweets and Search return iter.Seq2[Tweet, error]; the loop body receives one tweet at a time, and the next page is fetched only when the caller keeps ranging.

Early exit is free. When the caller writes break, yield returns false and the iterator returns before sending another request, so taking the first five tweets costs one page, not maxPages.

Loop on the flag, not the count. In our sample 30 of 75 pages held fewer than 20 tweets (the smallest held 12) while has_next_page was still true. A loop that stops on len(tweets) < 20 would have quit early on many accounts. Stop when has_next_page is false or next_cursor is empty, and pass the cursor back as cursor.

Errors travel in the second value. An error is yielded once and then the iterator stops, so the caller handles it in the same loop. The two endpoints differ only in where the tweets sit: under data.tweets for /twitter/user/last_tweets, at the top level for /twitter/tweet/advanced_search, which is why they decode into two small response structs. On Go 1.22 or older, the same logic works as a method that takes a callback func(Tweet) bool.

go
package twitterapi

import (
	"context"
	"iter"
	"net/url"
)

// UserInfo returns one profile (/twitter/user/info nests it under data).
func (c *Client) UserInfo(ctx context.Context, userName string) (*User, error) {
	var r userInfoResponse
	if err := c.Get(ctx, "/twitter/user/info", url.Values{"userName": {userName}}, &r); err != nil {
		return nil, err
	}
	return r.Data, nil
}

// LastTweets yields an account's tweets, newest first, across up to maxPages pages.
// Range over it with: for tw, err := range c.LastTweets(ctx, "golang", 3) { ... }
func (c *Client) LastTweets(ctx context.Context, userName string, maxPages int) iter.Seq2[Tweet, error] {
	return func(yield func(Tweet, error) bool) {
		q := url.Values{"userName": {userName}}
		for page := 0; page < maxPages; page++ {
			var r lastTweetsResponse
			if err := c.Get(ctx, "/twitter/user/last_tweets", q, &r); err != nil {
				yield(Tweet{}, err)
				return
			}
			for _, tw := range r.Data.Tweets {
				if !yield(tw, nil) { // caller used break: stop before the next request
					return
				}
			}
			// Loop on has_next_page, never on len(tweets) < 20: short pages are normal.
			if !r.HasNextPage || r.NextCursor == "" {
				return
			}
			q.Set("cursor", r.NextCursor)
		}
	}
}

// Search yields /twitter/tweet/advanced_search results (tweets at the top level).
func (c *Client) Search(ctx context.Context, query, queryType string, maxPages int) iter.Seq2[Tweet, error] {
	return func(yield func(Tweet, error) bool) {
		q := url.Values{"query": {query}, "queryType": {queryType}}
		for page := 0; page < maxPages; page++ {
			var r searchResponse
			if err := c.Get(ctx, "/twitter/tweet/advanced_search", q, &r); err != nil {
				yield(Tweet{}, err)
				return
			}
			for _, tw := range r.Tweets {
				if !yield(tw, nil) {
					return
				}
			}
			if !r.HasNextPage || r.NextCursor == "" {
				return
			}
			q.Set("cursor", r.NextCursor)
		}
	}
}
05 — Section

A runnable main package with context cancellation

The program below reads the key from TWITTERAPI_IO_KEY, prints one profile, shows how an unknown account surfaces, ranges over two timeline pages and one page of search. signal.NotifyContext cancels every in-flight request on Ctrl-C, and context.WithTimeout caps the whole run; both reach the HTTP layer through http.NewRequestWithContext, and the backoff sleep also selects on ctx.Done().

What happened when we ran it. With Go 1.27.4 the program printed the @golang profile, reported the unknown account as HTTP 200 ... user not found, returned 38 tweets over two timeline pages (a short page again) and 20 results on one page of from:golang -filter:retweets. go vet and gofmt reported nothing. The search uses X's own operators, which /twitter/tweet/advanced_search accepts with queryType set to Latest or Top.

Put the three files from the sections above in a twitterapi package inside your module, and this main.go under cmd/demo. Each tweet returned costs 15 credits ($0.00015), so the cost line is a quick sanity check while you develop.

go
// go run ./cmd/demo      (TWITTERAPI_IO_KEY set in the environment)
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"os/signal"
	"time"

	"example.com/twitterapi-demo/twitterapi"
)

func main() {
	key := os.Getenv("TWITTERAPI_IO_KEY")
	if key == "" {
		log.Fatal("set TWITTERAPI_IO_KEY")
	}
	// Ctrl-C cancels every in-flight request through the context.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
	defer cancel()

	api := twitterapi.New(key)

	u, err := api.UserInfo(ctx, "golang")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("@%s  %d followers  id %s\n", u.UserName, u.Followers, u.ID)

	if _, err := api.UserInfo(ctx, "no_such_user_zz_8812"); twitterapi.IsNotFound(err) {
		fmt.Println("unknown account ->", err)
	}

	n := 0
	for tw, err := range api.LastTweets(ctx, "golang", 2) {
		if err != nil {
			log.Fatal(err)
		}
		n++
		kind := "post"
		if tw.RetweetedTweet != nil {
			kind = "repost of @" + tw.RetweetedTweet.Author.UserName
		} else if tw.QuotedTweet != nil {
			kind = "quote"
		}
		if n <= 5 {
			fmt.Printf("%s  %s  %6d views  %d media  %s\n",
				tw.CreatedAt.Format(time.DateOnly), tw.ID, tw.ViewCount, len(tw.ExtendedEntities.Media), kind)
		}
	}
	fmt.Printf("%d tweets over 2 pages, about $%.4f at 15 credits per tweet\n", n, float64(n)*0.00015)

	m := 0
	for tw, err := range api.Search(ctx, "from:golang -filter:retweets", "Latest", 1) {
		if err != nil {
			var apiErr *twitterapi.APIError
			if errors.As(err, &apiErr) {
				log.Fatalf("search failed with HTTP %d: %s", apiErr.Status, apiErr.Msg)
			}
			log.Fatal(err)
		}
		if m == 0 {
			fmt.Println("newest original post:", tw.URL)
		}
		m++
	}
	fmt.Println(m, "search results on one page")
}
06 — Section

Fetching many accounts concurrently under one rate limiter

Goroutines make it easy to send more requests than your plan allows. TwitterAPI.io allows 0.2 requests per second before the first payment, 20 once paid, 50 on Scale and 500 on Business, and up to 1,000 on request. The safe pattern is one limiter shared by every goroutine, waited on before every attempt (retries included), with a small worker pool that only decides how many requests can be in flight.

The limiter. golang.org/x/time/rate provides a token-bucket Limiter; rate.NewLimiter(rate.Limit(20), 1) allows 20 requests per second, and rate.Every(5*time.Second) expresses the 0.2 per second tier. Limiter.Wait(ctx) blocks until a token is free and returns early if the context is cancelled. The client declares its own one-method interface, so *rate.Limiter plugs in while the client package keeps no external dependency. Note that golang.org/x/time v0.16.0 declares go 1.26.0 in its go.mod, so go get raises your module's go line to 1.26; the client itself needs only Go 1.23 for iter.

What we measured. At one request per second the three-account fan-out below finished in 6.1 s. A ticker (time.NewTicker) with a shared channel also works if you prefer zero dependencies, but it does not handle bursts or context cancellation as cleanly.

go
// go get golang.org/x/time/rate && go run ./cmd/fanout
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	"golang.org/x/time/rate"

	"example.com/twitterapi-demo/twitterapi"
)

type result struct {
	account string
	tweets  int
	newest  time.Time
	err     error
}

func main() {
	api := twitterapi.New(os.Getenv("TWITTERAPI_IO_KEY"))
	// One limiter shared by every goroutine. Pick the rate from your tier:
	// rate.Every(5*time.Second) before the first payment (0.2 requests/s),
	// rate.Limit(20) once paid, 50 on Scale, 500 on Business.
	api.Limiter = rate.NewLimiter(rate.Limit(1), 1)

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	accounts := []string{"golang", "kubernetesio", "PrometheusIO"}
	jobs := make(chan string)
	results := make(chan result)
	var wg sync.WaitGroup
	for range 3 { // a small worker pool; the limiter, not the pool size, sets the pace
		wg.Add(1)
		go func() {
			defer wg.Done()
			for acct := range jobs {
				r := result{account: acct}
				for tw, err := range api.LastTweets(ctx, acct, 1) {
					if err != nil {
						r.err = err
						break
					}
					r.tweets++
					if tw.CreatedAt.After(r.newest) {
						r.newest = tw.CreatedAt.Time
					}
				}
				results <- r
			}
		}()
	}
	go func() {
		for _, a := range accounts {
			jobs <- a
		}
		close(jobs)
		wg.Wait()
		close(results)
	}()

	start := time.Now()
	for r := range results {
		if r.err != nil {
			log.Printf("%s: %v", r.account, r.err)
			continue
		}
		fmt.Printf("@%-14s %2d tweets, newest %s\n", r.account, r.tweets, r.newest.Format(time.DateOnly))
	}
	fmt.Printf("done in %s\n", time.Since(start).Round(100*time.Millisecond))
}
07 — Section

How often Go-ecosystem accounts post, and what reading them costs

The same sample answers the operational question for a Go service that watches accounts: how much is there to fetch? Usually little. @CloudNativeFdn posted 9.7 times a day in its sampled window, and @etcdio 0.06. @golang itself posted 0.1 times a day across the 1,151.0 days its 118 posts covered.

AccountPostsDays coveredPosts per dayReposts
@CloudNativeFdn11812.29.732.2%
@influxdb405.17.890.0%
@GoogleOSS8739.02.2351.7%
@grafana11353.62.1117.7%
@Docker2011.71.70.0%
@HashiCorp12084.81.420.0%
@kubernetesio120140.90.850.0%
@CockroachDB110198.90.5530.9%
@traefik120494.40.240.8%
@goreleaser88618.10.1431.8%
@golang1181,151.00.14.2%
@PrometheusIO1121,429.40.0824.1%
@gitlab1201,739.20.071.7%
@etcdio1161,946.70.0662.9%

That matters because an empty check is still billed the 15-credit minimum, $0.00015. Polling one account every 60 seconds for a month is 43,200 checks, $6.48 before any tweet is returned; every 5 minutes it is about $1.30. For a list of quiet accounts, one /twitter/tweet/advanced_search query such as from:golang OR from:kubernetesio OR from:PrometheusIO replaces several polls, and the tweets it returns are billed at $0.15 per 1,000.

TwitterAPI.io bills per result: 15 credits per tweet returned, $0.15 per 1,000 tweets, with the 15-credit minimum on a request that returns nothing; profiles are 18 credits each ($0.18 per 1,000), and follower or following lists cost 1 to 3 credits per user returned. X's pay-per-usage rate card lists $0.005 per post read, $0.010 per user read and $0.010 per follower or following read, with post reads capped at 3 million a month before Enterprise. Per 1,000 tweets that is $5 against $0.15, about 33x.

New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days). Purchased credits never expire, and subscription plans (Starter $29, Builder $99, Pro $199, Scale $499, Business $1,499 a month) are listed on the pricing page linked below.

Writing from Go. Posting, liking, retweeting and following run through an authenticated session rather than the API key alone: one /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, and each write such as /twitter/create_tweet_v2 or /twitter/follow_user_v2 then costs 60 credits ($0.0006), billed per HTTP 200 call. Every write acts as that X account, so X can rate-limit, lock or suspend it; keep a human pace and expect the session to need a fresh login from time to time. Send those as POST requests with a JSON body through the same http.Client.

08 — Section

How we collected this

Question. What does a Go client have to be ready for on real responses: which tweet fields arrive as null, {} or missing, the JSON types of ids, the size of counters, whether createdAt parses with time.RubyDate, how long a page takes and how large it is, and how often Go-ecosystem accounts post?

Accounts. 14 public organization accounts, each verified first with /twitter/user/info: @CloudNativeFdn, @influxdb, @GoogleOSS, @grafana, @Docker, @HashiCorp, @kubernetesio, @CockroachDB, @traefik, @goreleaser, @golang, @PrometheusIO, @gitlab, @etcdio.

Method and window. /twitter/user/last_tweets with default settings, newest first, up to six pages per account, deduplicated by id: 1,402 tweets on 75 pages, 45 of them full 20-tweet pages. Each account's window runs from its oldest to newest post in the sample. Collected in 2026 with 14 profile requests and 75 successful page requests (plus 2 page requests that failed after five attempts, which cut @Docker and @influxdb short), about 21,282 credits ($0.21). Response times were measured from a Python urllib client on one connection, from the moment the shared rate limiter released the request to the decoded body; page sizes are bodies re-serialized as compact UTF-8 JSON, not bytes on the wire. The Go code then ran against the live API with 10 more requests, and a Go test decoded all 75 saved pages into the structs above with 0 errors.

What the sample cannot show. These are English-leaning organization timelines fetched without replies, so inReplyToId was always null here; with includeReplies=true it will carry ids. Accounts that post long-form articles, polls or location-tagged posts will populate article, card and place more often. Timing reflects one connection on one day and is not a service-level figure.

Privacy. Aggregates only, organization accounts only; reposted, quoted and mentioned authors are not analyzed. Raw pages are kept in the repository only where a page contains five or fewer distinct authors.

python
"""check_go_fields.py - pull timeline pages from TwitterAPI.io and report, per field, how often it
arrives as null, {} / [], missing, or with content. Use it to decide pointer vs value types
in your Go structs for the accounts you care about.

    pip install requests
    export TWITTERAPI_IO_KEY=...      # from the twitterapi.io dashboard
    python check_go_fields.py golang kubernetesio
"""
import os
import sys
from collections import Counter

import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
FIELDS = ["retweeted_tweet", "quoted_tweet", "card", "extendedEntities", "place",
          "viewCount", "inReplyToId", "communityInfo", "article"]


def timeline(user_name, max_pages=3):
    cursor = None
    for _ in range(max_pages):
        params = {"userName": user_name}
        if cursor:
            params["cursor"] = cursor
        r = requests.get(f"{BASE}/twitter/user/last_tweets", headers=HEADERS, params=params, timeout=30)
        if r.status_code == 400:
            raise SystemExit(f"bad request: {r.text}")  # HTTP 400 names the bad parameter
        r.raise_for_status()
        body = r.json()
        if body.get("status") == "error":
            raise SystemExit(body.get("msg"))
        yield from (body.get("data") or {}).get("tweets") or []
        # short pages are normal: loop on has_next_page, not on the page size
        if not body.get("has_next_page") or not body.get("next_cursor"):
            return
        cursor = body["next_cursor"]


def state(tweet, key):
    if key not in tweet:
        return "missing"
    value = tweet[key]
    if value is None:
        return "null"
    if value in ({}, [], ""):
        return "empty"
    return "content"


def main():
    users = sys.argv[1:] or ["golang"]
    tweets = [t for u in users for t in timeline(u)]
    if not tweets:
        raise SystemExit("no tweets returned")
    n = len(tweets)
    print(f"{n} tweets from {', '.join('@' + u for u in users)}")
    for key in FIELDS:
        c = Counter(state(t, key) for t in tweets)
        hint = "*T pointer" if c["null"] else ("value, check len()" if c["empty"] else "value")
        print(f"  {key:18} null {c['null']:4}  empty {c['empty']:4}  missing {c['missing']:4}  "
              f"content {c['content']:4}  -> {hint}")
    print(f"  id JSON types: {Counter(type(t['id']).__name__ for t in tweets)}")
    print(f"  cost: about ${n * 0.00015:.4f} at 15 credits per tweet returned")


if __name__ == "__main__":
    main()

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

09 — Questions

Questions readers ask

Is there an official Go SDK for the Twitter (X) API?

X does not publish one. Community libraries target X's own OAuth API: dghubble/go-twitter is archived and was written for v1.1, g8rswimmer/go-twitter/v2 has had no commits since December 2022, and michimani/gotwi is maintained and still describes itself as under development. For TwitterAPI.io no SDK is needed; net/http and encoding/json are enough.

How do I get a user's tweets in Go?

Send GET https://api.twitterapi.io/twitter/user/last_tweets?userName=<handle> with your key in X-API-Key, decode the body into a response struct whose Data field (tag json:"data") holds Tweets []Tweet (tag json:"tweets"), and pass next_cursor back as cursor while has_next_page is true. The LastTweets iterator on this page wraps exactly that.

Should tweet ids be int64 or string in Go?

Use string. All 1,402 ids in our sample arrived as 19-digit JSON strings, so decoding them into int64 would fail, and you never do arithmetic on an id. Strings also survive a JSON round trip to a JavaScript front end, where numbers above 2^53 lose precision.

How do I parse the createdAt field in Go?

Use time.Parse(time.RubyDate, s). The format Thu Oct 16 12:34:56 +0000 2026 is exactly Go's predefined RubyDate layout (Mon Jan 02 15:04:05 -0700 2006), and every createdAt in our sample parsed with it. Wrap it in a custom type with UnmarshalJSON so it decodes automatically.

Pointer or value for quoted_tweet, retweeted_tweet and extendedEntities?

Pointer for quoted_tweet and retweeted_tweet, because they come back as null unless set (1,357 and 1,129 of 1,402 tweets). Value for extendedEntities, because it was {} rather than null when a tweet had no media, so a pointer would always be non-nil; check len(Media) instead.

How do I respect rate limits with goroutines?

Share one rate.Limiter from golang.org/x/time/rate across all goroutines and call Wait(ctx) before every request, including retries. Set it to your tier: 0.2 requests per second before the first payment (rate.Every(5*time.Second)), 20 once paid, 50 on Scale, 500 on Business. Retry HTTP 429 with backoff in case several processes share a key.

How much does reading tweets from Go cost?

TwitterAPI.io charges 15 credits per tweet returned, $0.15 per 1,000 tweets, with a 15-credit ($0.00015) minimum on a request that returns nothing. X's pay-per-usage rate card lists $0.005 per post read, $5 per 1,000. New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days).

Can a Go program post tweets through TwitterAPI.io?

Yes, through an authenticated session: one /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, then each write such as /twitter/create_tweet_v2 costs 60 credits ($0.0006), billed per HTTP 200 call. The write acts as that X account, so X can rate-limit, lock or suspend it; keep a human pace and expect occasional re-login.

10 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.