Skip to content

Go (net/http)

Idiomatic net/http with request contexts, struct decoding, and back-off on 429.

Go ships net/http with everything you need to call a JSON API in production: configurable transports, request contexts for cancellation and deadlines, and a streaming body reader that works well with encoding/json. You almost never need a third-party client. This guide walks through the GoRest endpoints with patterns you can copy into a real service.

Setup

Define a small client struct that holds the base URL, the access token, and a long-lived *http.Client. Reusing the client is important; every fresh http.Client opens new TCP+TLS connections, which adds 100+ ms per request to a public API.

package gorest

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "strconv"
    "time"
)

type Client struct {
    BaseURL string
    Token   string
    HTTP    *http.Client
}

func New(token string) *Client {
    return &Client{
        BaseURL: "https://gorest.co.in/public/v3",
        Token:   token,
        HTTP:    &http.Client{Timeout: 15 * time.Second},
    }
}

Send the bearer token

Wrap the request creation so you cannot forget the Authorization header. Always pass a context; even an immediate timeout from the caller is useful when the upstream is slow.

func (c *Client) newRequest(ctx context.Context, method, path string, body any) (*http.Request, error) {
    var rdr io.Reader
    if body != nil {
        buf, err := json.Marshal(body)
        if err != nil { return nil, err }
        rdr = bytes.NewReader(buf)
    }
    req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, rdr)
    if err != nil { return nil, err }
    req.Header.Set("Authorization", "Bearer "+c.Token)
    req.Header.Set("Accept", "application/json")
    if body != nil {
        req.Header.Set("Content-Type", "application/json")
    }
    return req, nil
}

List users

Define a struct that matches the shape the API returns, then decode straight into it. A list is {data, meta}, so a small generic Page type holds both. Ids are UUID strings. Build the query string with url.Values rather than joining strings by hand (it escapes the brackets, which the API accepts). To get the next page, call again with Meta.NextCursor while Meta.HasMore is true.

type User struct {
    ID     string `json:"id"` // a UUID string
    Name   string `json:"name"`
    Email  string `json:"email"`
    Status string `json:"status"`
}

type Page[T any] struct {
    Data []T `json:"data"`
    Meta struct {
        HasMore    bool    `json:"has_more"`
        NextCursor *string `json:"next_cursor"`
    } `json:"meta"`
}

// ListUsers returns one page. Pass the previous page's cursor ("" for the first page).
func (c *Client) ListUsers(ctx context.Context, status, after string) (*Page[User], error) {
    q := url.Values{}
    q.Set("filter[status]", status)
    q.Set("page[size]", "25")
    if after != "" {
        q.Set("page[after]", after)
    }
    req, err := c.newRequest(ctx, "GET", "/users?"+q.Encode(), nil)
    if err != nil { return nil, err }
    res, err := c.HTTP.Do(req)
    if err != nil { return nil, err }
    defer res.Body.Close()
    if res.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("list users: %s", res.Status)
    }
    var page Page[User]
    if err := json.NewDecoder(res.Body).Decode(&page); err != nil {
        return nil, err
    }
    return &page, nil
}

Fetch a single user

var ErrNotFound = fmt.Errorf("not found")

func (c *Client) GetUser(ctx context.Context, id string) (*User, error) {
    req, err := c.newRequest(ctx, "GET", "/users/"+url.PathEscape(id), nil)
    if err != nil { return nil, err }
    res, err := c.HTTP.Do(req)
    if err != nil { return nil, err }
    defer res.Body.Close()
    if res.StatusCode == http.StatusNotFound { return nil, ErrNotFound }
    if res.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("get user %s: %s", id, res.Status)
    }
    var u User
    return &u, json.NewDecoder(res.Body).Decode(&u)
}

Create, update, delete

The three writes use POST, PATCH and DELETE (there is no PUT in v3), and the token needs the users:write scope. Use a separate struct for the request body so you do not send fields the API does not expect (id in particular).

type UserInput struct {
    Name   string `json:"name"`
    Email  string `json:"email"`
    Status string `json:"status,omitempty"` // defaults to "active"
}

func (c *Client) CreateUser(ctx context.Context, in UserInput) (*User, error) {
    req, err := c.newRequest(ctx, "POST", "/users", in)
    if err != nil { return nil, err }
    res, err := c.HTTP.Do(req)
    if err != nil { return nil, err }
    defer res.Body.Close()
    if res.StatusCode != http.StatusCreated {
        return nil, fmt.Errorf("create user: %s", res.Status)
    }
    var u User
    return &u, json.NewDecoder(res.Body).Decode(&u)
}

A 422 carries a Problem Details body with an errors array. Decode it and return it as a typed error so your callers can branch on it:

type FieldError struct {
    Pointer string `json:"pointer"` // for example "/email"
    Code    string `json:"code"`    // for example "taken"
    Detail  string `json:"detail"`
}
type ValidationError struct{ Errors []FieldError }

func (v ValidationError) Error() string {
    return fmt.Sprintf("validation: %d field(s) failed", len(v.Errors))
}

// ... inside CreateUser, before the 201 check:
if res.StatusCode == http.StatusUnprocessableEntity {
    var problem struct {
        Errors []FieldError `json:"errors"`
    }
    if err := json.NewDecoder(res.Body).Decode(&problem); err != nil {
        return nil, err
    }
    return nil, ValidationError{Errors: problem.Errors}
}

Retry on rate limits

Put a small back-off in your transport rather than in every caller. Use a custom http.RoundTripper so retries happen without the caller knowing. The Retry-After header is in seconds:

type retryTransport struct{ base http.RoundTripper }

func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    for attempt := 0; attempt < 3; attempt++ {
        res, err := t.base.RoundTrip(req)
        if err != nil { return nil, err }
        if res.StatusCode != http.StatusTooManyRequests { return res, nil }
        wait, _ := strconv.Atoi(res.Header.Get("Retry-After"))
        if wait < 1 { wait = 1 }
        res.Body.Close()
        select {
        case <-time.After(time.Duration(wait) * time.Second):
        case <-req.Context().Done():
            return nil, req.Context().Err()
        }
    }
    return nil, fmt.Errorf("rate limited; gave up")
}

// wire it on the client:
c.HTTP.Transport = &retryTransport{base: http.DefaultTransport}

Tips

  • Always defer res.Body.Close(). Skipping it leaks file descriptors and prevents connection reuse.
  • json.NewDecoder is more efficient than json.Unmarshal for HTTP responses, with no extra buffer.
  • The default http.Client has no timeout. Always set one (15 seconds is reasonable).
  • Define request structs separately from response structs even when the fields overlap. That makes it harder to send id or created_at back by mistake when updating.
Related guides

Keep going