client

package
v14.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 14 Imported by: 0

README

Iris HTTP Client

The client package calls other HTTP services. You configure a base URL, timeouts, rate limits and a retry policy once, then make requests against it. Request and response handling is pluggable, so you can add your own middleware to every call.

It is a thin layer over github.com/kataras/httpclient, the author's standalone client. Every type, option and function of that module is available here under the same name, so an Iris application imports only this package. What this package adds is the framework's defaults: request and response bodies follow the Iris JSON policy (core/pkg/jsonutil, the same one ctx.JSON and ctx.ReadJSON use on the server side), and Debug(nil) logs through golog.

Features

  • Base URL, timeouts, persistent request options
  • Typed responses through generic methods (BindJSON[T], BindPlain[T])
  • Rate limits per client, per endpoint, or one budget shared by several clients
  • Retries with exponential backoff, Retry-After honoured
  • Query parameter and header redaction in error messages and debug output
  • OAuth2 tokens through golang.org/x/oauth2
  • Request handlers (middleware) around every call
  • JSON, form and multipart file uploads
  • Errors that rest/errors.HandleAPIError forwards to your own client

Installation

import "github.com/kataras/iris/v14/client"

Configuration

Base URL and timeouts
c := client.New(
    client.BaseURL("https://api.example.com"),
    client.Timeout(15 * time.Second),      // the whole request, body included
    client.DialTimeout(10 * time.Second),  // connecting only
)

There is no default timeout. Set one for anything talking to the internet.

Persistent request options

Options that apply to every request:

c := client.New(
    client.PersistentRequestOptions(
        client.RequestAuthorizationBearer("YOUR_TOKEN"),
        client.RequestParam("apiKey", key),
    ),
)
Rate limiting
c := client.New(client.RateLimit(10)) // 10 requests per second

RateLimit covers the whole API. When one endpoint has a tighter budget, register a named limiter and tag the calls that use it. Every call sharing the key shares the budget, retries included:

c := client.New(
    client.RateLimit(20),                  // the whole API
    client.RateLimitFor("search", 2),      // this endpoint
)

results, err := c.BindJSON[Results](ctx, http.MethodGet, "/search", nil,
    client.RequestRateLimit("search"))

A Clone builds its own limiters. When several clients must share one upstream quota, build the limiter yourself and hand the same one to each with RateLimiter(l) or RateLimiterFor(key, l):

var hostLimiter = client.NewRateLimiter(20)

content := client.New(client.BaseURL(host+"/rest"), client.RateLimiter(hostLimiter))
catalogue := client.New(client.BaseURL(host), client.RateLimiter(hostLimiter))

A Limiter is any type with Wait(ctx) error, so a distributed limiter of your own fits too.

Retries

Retrying is opt-in. By default only network errors on idempotent methods (GET, HEAD, OPTIONS, TRACE, PUT, DELETE and QUERY) and the 429, 502, 503 and 504 statuses are retried; buffered request bodies are replayed.

c := client.New(
    client.BaseURL("https://api.example.com"),
    client.Retry(client.RetryPolicy{
        MaxAttempts:    3,
        InitialBackoff: 500 * time.Millisecond,
        MaxBackoff:     10 * time.Second,
        Jitter:         true,
    }),
)

Every attempt waits on the rate limiter and is visible to the request handlers, so Debug output shows the failed attempts as well.

OAuth2
c := client.New(client.OAuth2(oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})))

Or with an oauth2.Config that refreshes tokens on its own: client.OAuth2(config.TokenSource(ctx, token)). Give Transport, Handler or DialTimeout before it, since it wraps whatever transport is set at that point.

Request handlers

Run code before and after each request:

type MyRequestHandler struct{}

func (h *MyRequestHandler) BeginRequest(ctx context.Context, req *http.Request) error {
    return nil
}

func (h *MyRequestHandler) EndRequest(ctx context.Context, resp *http.Response, err error) error {
    return nil
}

c := client.New()
c.RegisterRequestHandler(&MyRequestHandler{})

A non-nil error from either method stops the call. An EndRequest handler that returns the error it was given passes it through.

Debugging
c := client.New(client.Debug(nil))          // golog, "Iris HTTP Client" child at debug level
c := client.New(client.Debug(app.Logger())) // the application's logger

Both dumps, request and response, go to the logger. Values of query parameters registered with RedactQueryParams, and the Authorization, Proxy-Authorization, Cookie and Set-Cookie headers, are replaced by REDACTED:

c := client.New(
    client.PersistentRequestOptions(client.RequestParam("apiKey", key)),
    client.RedactQueryParams("apiKey"),
    client.Debug(nil),
)

The same redaction applies to APIError messages. Request and response bodies are never scrubbed.

Testing against a handler
c := client.New(client.Handler(app)) // any http.Handler, an *iris.Application included

Requests are served in-process. The response is recorded in full before the client sees it, so for a streaming handler use client.Transport(srv.Client().Transport) with an httptest.NewTestServer instead.

Usage

Sending requests
type Payload struct {
    Name string `json:"name"`
}

resp, err := c.JSON(context.Background(), http.MethodPost, "/endpoint", Payload{Name: "John"})
if err != nil {
    panic(err)
}
c.DrainResponseBody(resp)
resp, err := c.Form(context.Background(), http.MethodPost, "/endpoint", url.Values{
    "field1": {"value1"},
    "field2": {"value2"},
})
if err != nil {
    panic(err)
}
c.DrainResponseBody(resp)

Do, JSON, Form and Uploader.Upload hand you the *http.Response with its body still open and do not inspect the status. Closing it is your job, and DrainResponseBody is how to do it so the connection can be reused. Everything under "Reading responses" closes it for you.

Reading responses

BindJSON names the response type at the call site and returns it:

type Response struct {
    Data string `json:"data"`
}

respData, err := c.BindJSON[Response](context.Background(), http.MethodGet, "/endpoint", nil)

The type parameter is the response type; the arguments are the request method, URL path, an optional payload (sent as JSON when non-nil) and any request options. A status of 400 or above comes back as an APIError.

ReadJSON fills a value you already hold, which is what you want for a long-lived field or a pooled struct:

var respData Response
err := c.ReadJSON(context.Background(), &respData, http.MethodGet, "/endpoint", nil)

BindPlain[T] and ReadPlain do the same for plain text, into a string, []byte, int, int64 or float64:

respText, err := c.BindPlain[string](context.Background(), http.MethodGet, "/endpoint", nil)

Call is for endpoints whose success body carries nothing. It returns the APIError on a failure status and nil otherwise:

err := c.Call(context.Background(), http.MethodDelete, "/endpoint/42", nil)
Paginated lists

An Iris list endpoint answers a Page[T] (CurrentPage, TotalPages, TotalItems, HasNextPage, Items), reads the page and size from the URL and the filter from the body. List[T] fetches one page. It sends a QUERY request (RFC 10008), which the client retries like a GET:

page, err := client.List[Book](ctx, c, "/books", client.PageOptions{Page: 1, Size: 20}, filter)

Items[T] walks every page and hands you one item at a time. It stops when the server has no next page or when you break out of the loop:

for book, err := range client.Items[Book](ctx, c, "/books", filter, client.PageSize(50)) {
    if err != nil {
        return err
    }
    fmt.Println(book.Title)
}

A server that still lists over POST takes client.ListMethod(http.MethodPost) as one more option. PageOptions, Page[T], CountResponse[N] and ListFilter are the same types the server uses (iris.Page[T] and so on), from the std-only core/pkg/pagination package.

An empty JSON body comes back as io.EOF, which IsErrEmptyJSON also recognises. Bind[T](resp) decodes a response you already hold, choosing by Content-Type.

File uploads
uploader := c.NewUploader()
uploader.AddFile("file", "path/to/file.txt")
resp, err := uploader.Upload(context.Background(), http.MethodPost, "/upload")
if err != nil {
    panic(err)
}
c.DrainResponseBody(resp)

An Uploader sends once; a second Upload returns ErrUploaderClosed.

Error handling

Extracting errors

Do returns the response as-is, whatever its status. ExtractError wraps a failed response (reading and closing its body) into an APIError:

resp, err := c.Do(context.Background(), http.MethodGet, "/endpoint", nil)
if err != nil {
    panic(err) // transport failure, there is no response to extract from.
}

if resp.StatusCode >= 400 {
    apiErr := client.ExtractError(resp)
    fmt.Println(apiErr.Error()) // "https://api.example.com/endpoint: 404 Not Found: {...}"
}

The typed readers (BindJSON, ReadJSON, BindPlain, ReadPlain, Call) do this for you and return the APIError as their error. APIError.Code() is the status, APIError.Body the raw body.

Decoding errors

BindError decodes the body of an APIError into any JSON type. When the remote server is an Iris application using the rest/errors package, the body is its wire error envelope, so decode straight into errors.Error:

import "github.com/kataras/iris/v14/rest/errors"

_, err := c.BindJSON[Response](context.Background(), http.MethodGet, "/endpoint", nil)
if err != nil {
    remoteErr, decodeErr := client.BindError[errors.Error](err)
    if decodeErr != nil {
        panic(decodeErr) // not an APIError, or the body is not JSON.
    }
    fmt.Println(remoteErr.ErrorCode.CanonicalName, remoteErr.Message)
}

DecodeError(err, &dest) is the pointer form. Inside an Iris handler, errors.HandleAPIError(ctx, err) forwards the remote envelope to your own client instead. Because client.APIError is the same type as httpclient.APIError, that also works for errors produced by services that use github.com/kataras/httpclient directly.

Status codes

GetErrorCode reads the status of an APIError. It returns 0 for a nil error, for any error that is not an APIError (a transport failure from Do, for example) and for an APIError built without a response, so check for zero before using the result as a status:

_, err := c.BindJSON[Response](context.Background(), http.MethodGet, "/endpoint", nil)
if client.GetErrorCode(err) == http.StatusNotFound {
    // ...
}

GetError(err) returns the APIError itself, found through errors.As, so an error wrapped with %w is still recognised.

Building against a local checkout

This package requires a published version of github.com/kataras/httpclient. To develop the two together, use a Go workspace from this repository's root; go.work is ignored by git and by dependents:

go work init . ../httpclient

References

Documentation

Overview

Package client is an HTTP client for sending requests to remote services and decoding their responses.

It is a thin layer over github.com/kataras/httpclient: every type, option and function of that package is available here under the same name, so an Iris application never imports it directly. What this package adds is the framework's defaults. Request payloads and response bodies follow the Iris JSON policy of core/pkg/jsonutil (time.Duration as int64 nanoseconds, sorted map keys, case-insensitive member matching, duplicate members rejected), the same policy the server side uses in ctx.JSON and ctx.ReadJSON, and Debug(nil) logs through golog.

The central type is Client, created with New and configured through Options such as a base URL, a timeout, persistent request options, rate limiters, a retry policy and before/after request handlers:

c := client.New(
	client.BaseURL("https://api.example.com/v1"),
	client.Timeout(30*time.Second),
	client.PersistentRequestOptions(client.RequestAuthorizationBearer(token)),
)

Reading responses

BindJSON names the response type at the call site and returns it:

user, err := c.BindJSON[User](ctx, http.MethodGet, "/users/42", nil)

ReadJSON fills a value you already hold, which is what you want for a long-lived field or a pooled struct:

var user User
err := c.ReadJSON(ctx, &user, http.MethodGet, "/users/42", nil)

BindPlain and ReadPlain do the same for plain text bodies. Call is for endpoints whose success body carries nothing. WriteTo copies the body to a writer, forwarding Content-Type and Content-Length when that writer is an http.ResponseWriter. All of them close the response body and turn a status of 400 or above into an APIError, which rest/errors.HandleAPIError knows how to forward to your own client.

Owning the response body

Do, JSON, Form and Uploader.Upload hand you the *http.Response with its body still open. Close it with DrainResponseBody so the connection can be reused.

Options

Client options, passed to New or Clone:

BaseURL, Timeout, DialTimeout, Transport, Handler, OAuth2,
PersistentRequestOptions,
RateLimit, RateLimitPerMinute, RateLimitFor, RateLimitForPerMinute,
RateLimiter, RateLimiterFor,
Retry, RedactQueryParams, RedactHeaders,
JSONOptions, JSONMarshalOptions, JSONUnmarshalOptions, Debug, NoOption

Request options, passed to any request method:

RequestHeader, RequestAuthorization, RequestAuthorizationBearer,
RequestQuery, RequestParam, RequestRateLimit, ClientTrace

Index

Constants

View Source
const MethodQuery = "QUERY"

MethodQuery is the RFC 10008 QUERY method: a safe, idempotent request that carries a body, the shape of a search or a filtered list. The client retries it like GET. It becomes http.MethodQuery once go.mod requires Go 1.28.

Variables

View Source
var ErrUploaderClosed = httpclient.ErrUploaderClosed

ErrUploaderClosed is returned when an Uploader is used for a second upload.

View Source
var IsErrEmptyJSON = httpclient.IsErrEmptyJSON

IsErrEmptyJSON reports whether "err" comes from a BindJSON or ReadJSON call whose response body was empty, which several APIs answer to a successful write. It is a variable so that it can be replaced.

Functions

func Bind

func Bind[T any](resp *http.Response, opts ...json.Options) (T, error)

Bind decodes an already-received response into a new T, choosing the decoder from the response's Content-Type header (JSON, or plain text into a string or byte slice). Closing the response body is up to the caller.

JSON bodies decode under the Iris policy; "opts" are joined on top of it.

func BindError

func BindError[T any](err error, opts ...json.Options) (T, error)

BindError decodes the JSON body carried by the APIError inside "err" into a new T. When the remote server is an Iris application, that body is the rest/errors envelope:

remote, decodeErr := client.BindError[errors.Error](err)

It returns the original "err" untouched when "err" does not carry an APIError, so "not an API error" stays distinguishable from "an API error I could not decode".

func DecodeError

func DecodeError(err error, destPtr any, opts ...json.Options) error

DecodeError binds the JSON body of an APIError to "destPtr". It returns the original "err" when it is not an APIError. Prefer the generic BindError.

func DrainResponseBody

func DrainResponseBody(resp *http.Response) error

DrainResponseBody drains the response body and closes it, allowing the transport to reuse TCP connections. A nil response or a nil body is a no-op. The BindXXX, ReadXXX, Call and WriteTo methods do it for you.

func GetErrorCode

func GetErrorCode(err error) int

GetErrorCode reads an error, which should be an APIError, and returns its status code. It returns zero when "err" is nil, is not an APIError, or carries no response. Check for zero before using the result as a status.

func Items

func Items[T any](ctx context.Context, c *Client, urlpath string, filter any, opts ...RequestOption) iter.Seq2[T, error]

Items walks a paginated list item by item, requesting page after page through List until the server reports no next page, a page comes back empty, or the loop breaks. A failed request yields its error once, with the zero T, and ends the walk.

for book, err := range client.Items[Book](ctx, c, "/books", filter, client.PageSize(50)) {
	if err != nil {
		return err
	}
	// use book.
}

func RedactURL

func RedactURL(u *url.URL, keys ...string) string

RedactURL returns the string form of "u" with the values of the given query parameters replaced by "REDACTED" and any userinfo password masked, for your own log lines.

func RegisterRequestHandler

func RegisterRequestHandler(reqHandlers ...RequestHandler)

RegisterRequestHandler registers one or more request handlers to run before and after each request on all Clients created afterwards, by this package or by github.com/kataras/httpclient directly. Useful for third-party libraries, e.g. to register request-response lifecycle logging on init.

Types

type APIError

type APIError = httpclient.APIError

APIError is the error returned for a response with a status of 400 or above. Response holds the response, Body its raw body, already read and closed. Server code builds APIError values too, so Response, its Request and the Body may each be nil.

func ExtractError

func ExtractError(resp *http.Response) APIError

ExtractError returns the response wrapped inside an APIError, reading and closing its body. A nil response yields the zero APIError.

func GetError

func GetError(err error) (APIError, bool)

GetError reports whether the given "err" is, or wraps, an APIError. It reports false for an APIError carrying no response, so that callers can read apiErr.Response without a nil check.

type Client

type Client = httpclient.Client

A Client is an HTTP client. Initialize with the New package-level function.

It is github.com/kataras/httpclient.Client, so every method of that type is available: Do, JSON, Form, Call, BindJSON, BindPlain, ReadJSON, ReadPlain, GetPlainUnquote, WriteTo, NewUploader, Clone, RegisterRequestHandler and DrainResponseBody.

func New

func New(opts ...Option) *Client

New returns a new Iris HTTP Client with the framework's JSON policy applied, then the given options in order. See the package documentation for the available options.

The default content type to send and receive data is JSON.

type CountResponse

type CountResponse[N pagination.CountType] = pagination.CountResponse[N]

CountResponse is the response of a count endpoint.

type DebugLogger

type DebugLogger = httpclient.DebugLogger

A DebugLogger receives the request and response dumps of the Debug option. *golog.Logger satisfies it.

var DefaultDebugLogger DebugLogger = golog.Child("Iris HTTP Client: ").SetLevel("debug")

DefaultDebugLogger is the logger Debug uses when handed nil: a golog child named "Iris HTTP Client" at debug level. Replace it before creating clients to route the dumps elsewhere.

type Limiter

type Limiter = httpclient.Limiter

A Limiter blocks until the next request may be sent. *rate.Limiter of golang.org/x/time/rate satisfies it, and NewRateLimiter returns one.

func NewRateLimiter

func NewRateLimiter(requestsPerSecond int) Limiter

NewRateLimiter returns a Limiter allowing requestsPerSecond requests per second with a burst of the same size, to hand to RateLimiter or RateLimiterFor. Zero or less returns nil.

func NewRateLimiterPerMinute

func NewRateLimiterPerMinute(requestsPerMinute int) Limiter

NewRateLimiterPerMinute is NewRateLimiter expressed per minute.

type ListFilter

type ListFilter = pagination.ListFilter

ListFilter is the filter half every Iris list endpoint shares: term, names, substring and sort. Embed it in the filter sent as the body.

type Option

type Option = httpclient.Option

Option configures a Client. Pass options to New or Client.Clone.

var NoOption Option = func(c *Client) {
	httpclient.NoOption(c)
	irisDefaults(c)
}

NoOption clears the options recorded before it, so a Clone that starts with it keeps none of the parent's, and then re-applies the Iris JSON defaults so they survive the reset:

admin := c.Clone(client.NoOption, client.BaseURL(adminURL))

It is recorded in the option list like any other option, so a clone of that clone re-applies the defaults too.

func BaseURL

func BaseURL(uri string) Option

BaseURL registers the base URL of this client. All of its methods prepend this URL to the given path, with a trailing "/" trimmed from the base.

func Debug

func Debug(logger DebugLogger) Option

Debug enables the client's debug logger. It dumps each request right before it is sent and each response right after it is received, with redacted query parameters and credential headers replaced by "REDACTED". A nil logger uses DefaultDebugLogger.

c := client.New(client.Debug(nil))         // golog
c := client.New(client.Debug(app.Logger())) // the application's logger

func DialTimeout

func DialTimeout(timeout time.Duration) Option

DialTimeout specifies a time limit for establishing connections, name resolution included. It adjusts the Client's *http.Transport, cloning http.DefaultTransport when there is none yet, so proxy settings from the environment and the connection pool defaults are kept.

func Handler

func Handler(h http.Handler) Option

Handler specifies an iris.Application or any http.Handler that can be tested through this Client: requests are served in-process, without a network. The response is recorded in full before the Client sees it, so a streaming handler is better tested through Transport and an httptest.NewTestServer.

func JSONMarshalOptions

func JSONMarshalOptions(opts ...json.Options) Option

JSONMarshalOptions replaces the options used to encode request payloads (default jsonutil.DefaultMarshalOptions), leaving decoding alone.

func JSONOptions

func JSONOptions(opts ...json.Options) Option

JSONOptions replaces the encoding/json/v2 options this Client uses to encode payloads and decode bodies. The default is the Iris policy of core/pkg/jsonutil; options given here replace it for both directions, they are not merged with it. Join them with json.JoinOptions to keep both.

func JSONUnmarshalOptions

func JSONUnmarshalOptions(opts ...json.Options) Option

JSONUnmarshalOptions replaces the options used to decode response bodies (default jsonutil.DefaultUnmarshalOptions), leaving encoding alone.

func OAuth2

func OAuth2(src oauth2.TokenSource) Option

OAuth2 sends every request with a token from "src", wrapping the Client's transport in an oauth2.Transport. Give Transport, Handler or DialTimeout before it.

c := client.New(client.OAuth2(oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})))

or with a configuration that refreshes tokens on its own:

config := &oauth2.Config{...}
c := client.New(client.OAuth2(config.TokenSource(ctx, token)))

func PersistentRequestOptions

func PersistentRequestOptions(reqOpts ...RequestOption) Option

PersistentRequestOptions adds one or more request options that every request made by this Client will respect.

func RateLimit

func RateLimit(requestsPerSecond int) Option

RateLimit configures how many requests per second this Client may send. Every attempt, retries included, waits on the limiter. A Clone builds its own limiter. Zero or less disables rate limiting.

func RateLimitFor

func RateLimitFor(key string, requestsPerSecond int) Option

RateLimitFor registers a named limiter on top of the client-wide one. Requests select it with the RequestRateLimit request option:

c := client.New(client.RateLimit(20), client.RateLimitFor("search", 2))
results, err := c.BindJSON[Results](ctx, "GET", "/search", nil, client.RequestRateLimit("search"))

func RateLimitForPerMinute

func RateLimitForPerMinute(key string, requestsPerMinute int) Option

RateLimitForPerMinute is RateLimitFor expressed per minute.

func RateLimitPerMinute

func RateLimitPerMinute(requestsPerMinute int) Option

RateLimitPerMinute is RateLimit expressed per minute, with a burst of the whole minute's worth.

func RateLimiter

func RateLimiter(l Limiter) Option

RateLimiter sets a Limiter you own as the client-wide limiter, so several Clients can share one budget. A Clone shares it too. Nil disables limiting.

func RateLimiterFor

func RateLimiterFor(key string, l Limiter) Option

RateLimiterFor registers a Limiter you own under a name. Nil removes it.

func RedactHeaders

func RedactHeaders(names ...string) Option

RedactHeaders registers extra header names whose values are replaced by "REDACTED" in Debug output. Authorization, Proxy-Authorization, Cookie and Set-Cookie are always redacted.

func RedactQueryParams

func RedactQueryParams(keys ...string) Option

RedactQueryParams registers query parameter names (e.g. "apiKey") whose values must never appear in APIError messages or Debug output. The request itself is not modified.

func Retry

func Retry(policy RetryPolicy) Option

Retry enables automatic retries according to the policy: network errors on idempotent methods and the 429, 502, 503 and 504 statuses by default, with exponential backoff, a Retry-After header winning when present. Buffered request bodies are replayed. A policy with MaxAttempts below 2 disables it.

func Timeout

func Timeout(timeout time.Duration) Option

Timeout specifies a time limit for requests made by this Client, including connection time, redirects and reading the body. Zero, the default, means no timeout. Set one for anything talking to the internet.

func Transport

func Transport(rt http.RoundTripper) Option

Transport sets the http.RoundTripper the Client sends through, for an instrumented transport or the transport of an httptest.NewTestServer. Transport, DialTimeout and Handler all write the same field, the last wins.

type Page

type Page[T any] = pagination.Page[T]

Page is the response envelope of a paginated list.

func List

func List[T any](ctx context.Context, c *Client, urlpath string, page PageOptions, filter any, opts ...RequestOption) (*Page[T], error)

List fires one QUERY request to urlpath, with the page options in the URL query and "filter" as the JSON body, and decodes the Page of T it answers.

Pass ListMethod(http.MethodPost) for a server that lists over POST, and PageSize or any other RequestOption through "opts"; they run after the page options, so they win.

page, err := client.List[Book](ctx, c, "/books", client.PageOptions{Page: 1, Size: 20}, filter)

type PageOptions

type PageOptions = pagination.PageOptions

PageOptions is the page, size and details a list request carries in the URL query. Its Bind method is a RequestOption that writes them.

type PlainText

type PlainText = httpclient.PlainText

PlainText lists the Go types Client.BindPlain can produce from a plain text body: string, []byte, int, int64, float64 and named types over them.

type RequestHandler

type RequestHandler = httpclient.RequestHandler

RequestHandler observes every request. Its BeginRequest fires right before the client talks to the server and its EndRequest right after a response is received. A non-nil error from either stops the call; an EndRequest handler that returns the error it was given passes it through.

type RequestOption

type RequestOption = httpclient.RequestOption

RequestOption declares the type of option one can pass to the request methods (Do, JSON, Form, BindJSON, ReadJSON...). Request options run before the request is sent.

func ClientTrace

func ClientTrace(clientTrace *httptrace.ClientTrace) RequestOption

ClientTrace adds a client trace to the request.

func ListMethod

func ListMethod(method string) RequestOption

ListMethod replaces the method of a list request, e.g. ListMethod(http.MethodPost) for a server that does not answer QUERY yet.

func PageSize

func PageSize(size int) RequestOption

PageSize sets the "size" URL query parameter of a list request, the number of items per page. The server bounds it by its own maximum.

func RequestAuthorization

func RequestAuthorization(value string) RequestOption

RequestAuthorization sets an Authorization request header.

func RequestAuthorizationBearer

func RequestAuthorizationBearer(accessToken string) RequestOption

RequestAuthorizationBearer sets an Authorization: Bearer $token request header.

func RequestHeader

func RequestHeader(overridePrev bool, key string, values ...string) RequestOption

RequestHeader adds or sets (if overridePrev is true) a header to the request.

func RequestParam

func RequestParam(key string, values ...string) RequestOption

RequestParam sets a single URL query parameter to the request.

func RequestQuery

func RequestQuery(query url.Values) RequestOption

RequestQuery adds a set of URL query parameters to the request.

func RequestRateLimit

func RequestRateLimit(key string) RequestOption

RequestRateLimit makes the request wait on the named limiter registered with RateLimitFor, RateLimitForPerMinute or RateLimiterFor. An unknown key is a no-op.

type RetryPolicy

type RetryPolicy = httpclient.RetryPolicy

RetryPolicy configures automatic retries. Register it with Retry.

type Uploader

type Uploader = httpclient.Uploader

Uploader collects multipart form fields and files. See Client.NewUploader.

Jump to

Keyboard shortcuts

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