httpclient

package
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package httpclient builds configured *http.Client values for calling upstream services, and helps consume their JSON responses. It is the transport half of a typed service client (see `skit add http-client`): the generated client package builds one of these in its constructor, then its methods assemble requests and decode responses through DoJSON.

The transport is composed from httpmw middlewares — retry (429 and 503 by default, honoring Retry-After), a User-Agent, an idempotency key, arbitrary headers — and, when OAuth2 is configured, an OAuth2 client_credentials bearer. Composition order (httpmw.Chain) puts the idempotency key outermost, retry below it and auth innermost: every attempt of a call carries one key, and a retried attempt re-attaches the current token.

Usage

hc, err := httpclient.New(httpclient.Config{
	Name:           "billing",
	Metrics:        d.Metrics,
	UserAgent:      "billing-client",
	Retry:          &httpmw.RetryConfig{Backoff: retry.Backoff{MaxAttempts: 3}},
	TracerProvider: d.TracerProvider,
})
if err != nil {
	return err
}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
err = httpclient.DoJSON(hc, req, &out)

Tracing

Every attempt gets an OpenTelemetry client span (otelhttp) — a retried call shows each try — and sends its traceparent, so the upstream continues the caller's trace. The span sits below retry and the header decorations and above OAuth2: it sees the final headers, and the token fetch gets no span. A retry carries http.request.resend_count (httpmw.ResendCount). url.full has no user info, and the values of the signature query keys of the semantic conventions (AWSAccessKeyId, Signature, sig, X-Goog-Signature) read REDACTED. Pass the request context: the span is a child of the span in it.

Metrics

With Config.Metrics set, every attempt is recorded under the client's Name:

  • skit_http_client_requests_total by client, http_request_method, http_response_status_code and error_type;
  • skit_http_client_request_duration_seconds by client, with the span of the attempt as the exemplar.

A response is recorded with its status code and an empty error_type; a request that got no response with an empty status code and error_type canceled, timeout or _OTHER. A method the HTTP semantic conventions do not know is recorded as _OTHER.

Config

  • Name: the client label of the metrics (default "default").
  • Metrics: the registry of the request metrics; nil disables them.
  • Timeout: per-request timeout, retries included (default DefaultTimeout).
  • Retry: retry 429 and 503 (RetryConfig.Statuses), honoring Retry-After; nil disables retries.
  • OAuth2: client_credentials bearer; nil disables it.
  • UserAgent, Version, Environment: "product/version (env)" User-Agent.
  • IdempotencyHeader: an idempotency key per call, the same for its retries.
  • Headers: static headers on every request.
  • Base: the wire transport (default http.DefaultTransport).
  • TracerProvider: records the client spans; nil → the global provider.
Example

New builds the client of an upstream from one Config; DoJSON sends a request and decodes the JSON of a 2xx response.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/assanoff/skit/httpclient"
	"github.com/assanoff/skit/httpmw"
	"github.com/assanoff/skit/retry"
)

type invoice struct {
	ID     string `json:"id"`
	Amount int    `json:"amount"`
}

func main() {
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("upstream:", r.UserAgent())
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, `{"id":"inv-7","amount":1200}`)
	}))
	defer upstream.Close()

	hc, err := httpclient.New(httpclient.Config{
		Name:        "billing",
		UserAgent:   "shop",
		Version:     "1.4.0",
		Environment: "prod",
		Retry: &httpmw.RetryConfig{
			Backoff: retry.Backoff{Base: 100 * time.Millisecond, MaxAttempts: 3},
		},
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	req, err := http.NewRequestWithContext(context.Background(),
		http.MethodGet, upstream.URL+"/invoices/inv-7", nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	var inv invoice
	err = httpclient.DoJSON(hc, req, &inv)
	fmt.Println(inv.ID, inv.Amount, err)
}
Output:
upstream: shop/1.4.0 (prod)
inv-7 1200 <nil>

Index

Examples

Constants

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout is the per-request client timeout when Config.Timeout is unset.

Variables

This section is empty.

Functions

func DoJSON

func DoJSON(c *http.Client, req *http.Request, out any) error

DoJSON sends req through c, and on a 2xx response decodes the JSON body into out (skip decoding by passing a nil out). A non-2xx response yields a *StatusError; a transport error is returned as-is. The response body is always closed. An empty 2xx body is not an error (out is left unchanged).

Example

A response that is not 2xx is a *StatusError with the status and the start of the body, so the caller branches on the status.

package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/assanoff/skit/httpclient"
)

type invoice struct {
	ID     string `json:"id"`
	Amount int    `json:"amount"`
}

func main() {
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		http.Error(w, `{"code":"not_found"}`, http.StatusNotFound)
	}))
	defer upstream.Close()

	req, err := http.NewRequestWithContext(context.Background(),
		http.MethodGet, upstream.URL+"/invoices/inv-0", nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = httpclient.DoJSON(upstream.Client(), req, &invoice{})
	if se, ok := errors.AsType[*httpclient.StatusError](err); ok {
		fmt.Println(se.StatusCode)
	}
	fmt.Println(err)
}
Output:
404
http 404 Not Found: {"code":"not_found"}

func New

func New(cfg Config) (*http.Client, error)

New builds an *http.Client with the composed transport. It returns an error only when OAuth2 is set but invalid.

func OAuth2Transport

func OAuth2Transport(cfg OAuth2Config, base http.RoundTripper) (http.RoundTripper, error)

OAuth2Transport returns an http.RoundTripper that adds an OAuth2 client_credentials bearer token to every request, refreshing and caching it automatically, then delegates to base (or http.DefaultTransport when nil).

base is the wire transport — pass it here and compose retries/headers ABOVE this in the chain (httpmw.Chain), so a retried request re-attaches the current token. Token fetches use base too, so the TLS, proxy, dialer and instrumentation configured on it apply to the token endpoint as well; they run on a separate client bounded by TokenTimeout, outside the middleware layered above, so they are not themselves retried or wrapped.

Example

OAuth2Transport fetches a client_credentials token, caches it and sets it on every request. Compose it innermost, below the retry, so a retried attempt carries the current token.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/assanoff/skit/httpclient"
	"github.com/assanoff/skit/httpmw"
	"github.com/assanoff/skit/retry"
)

func main() {
	upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/token" {
			w.Header().Set("Content-Type", "application/json")
			fmt.Fprint(w, `{"access_token":"t-1","token_type":"bearer","expires_in":3600}`)
			return
		}
		fmt.Println("upstream:", r.Header.Get("Authorization"))
	}))
	defer upstream.Close()

	auth, err := httpclient.OAuth2Transport(httpclient.OAuth2Config{
		TokenURL:     upstream.URL + "/token",
		ClientID:     "shop",
		ClientSecret: "s3cret",
	}, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	hc := &http.Client{Transport: httpmw.Chain(auth,
		httpmw.Retry(httpmw.RetryConfig{Backoff: retry.Backoff{MaxAttempts: 3}}),
	)}

	for range 2 {
		req, err := http.NewRequestWithContext(context.Background(),
			http.MethodGet, upstream.URL+"/invoices", nil)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(httpclient.DoJSON(hc, req, nil))
	}
}
Output:
upstream: Bearer t-1
<nil>
upstream: Bearer t-1
<nil>

Types

type Config

type Config struct {
	// Name names the client in its metrics, the client label (default
	// "default"); give each client its own, e.g. the upstream's name.
	Name string
	// Metrics is the registry of the request metrics
	// (skit_http_client_requests_total,
	// skit_http_client_request_duration_seconds); nil disables them.
	Metrics prometheus.Registerer
	// Timeout is the per-request client timeout (default DefaultTimeout). It
	// bounds the whole call including retries.
	Timeout time.Duration
	// Retry, when non-nil, wraps the transport in retry: 429 and 503 by
	// default (RetryConfig.Statuses), honoring Retry-After.
	Retry *httpmw.RetryConfig
	// OAuth2, when non-nil, adds a client_credentials bearer token.
	OAuth2 *OAuth2Config
	// UserAgent, when non-empty, sets the User-Agent header (product name).
	UserAgent string
	// Version, Environment refine the User-Agent to "product/version (env)".
	Version     string
	Environment string
	// IdempotencyHeader, when non-empty, injects an idempotency key per call
	// under this header, the same for all its retries. A request that already
	// carries the header keeps its value.
	IdempotencyHeader string
	// Headers are static headers set on every request.
	Headers map[string]string
	// Base is the innermost (wire) transport (default http.DefaultTransport).
	// Business requests and the OAuth2 token fetch both go over it.
	Base http.RoundTripper
	// TracerProvider records a client span per attempt; nil → the global
	// provider.
	TracerProvider trace.TracerProvider
}

Config assembles an upstream HTTP client. All fields are optional except that OAuth2, when set, requires its own required fields. The zero Config yields a plain client with DefaultTimeout and no retry/auth.

type OAuth2Config

type OAuth2Config struct {
	// TokenURL is the full OAuth2 token endpoint.
	TokenURL string
	// ClientID, ClientSecret are the client_credentials grant.
	ClientID     string
	ClientSecret string
	// Scopes are requested with the token; may be empty.
	Scopes []string
	// TokenTimeout bounds each token fetch (default 10s). The token fetch runs
	// on its own client over the same wire transport as business requests.
	TokenTimeout time.Duration
}

OAuth2Config configures an OAuth2 client_credentials token source. TokenURL, ClientID and ClientSecret are required. Scopes are baked into the token source (a client needs one instance per scope set — the token cache is per source).

type StatusError

type StatusError struct {
	StatusCode int
	Status     string
	Body       []byte
}

StatusError is returned by DoJSON when the upstream responds with a non-2xx status. It carries the status and a (capped) snapshot of the body so callers can branch on StatusCode with errors.As and surface the upstream message.

func (*StatusError) Error

func (e *StatusError) Error() string

Error reports the status and, when present, the body snapshot.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL