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
- Variables
- func Bind[T any](resp *http.Response, opts ...json.Options) (T, error)
- func BindError[T any](err error, opts ...json.Options) (T, error)
- func DecodeError(err error, destPtr any, opts ...json.Options) error
- func DrainResponseBody(resp *http.Response) error
- func GetErrorCode(err error) int
- func Items[T any](ctx context.Context, c *Client, urlpath string, filter any, ...) iter.Seq2[T, error]
- func RedactURL(u *url.URL, keys ...string) string
- func RegisterRequestHandler(reqHandlers ...RequestHandler)
- type APIError
- type Client
- type CountResponse
- type DebugLogger
- type Limiter
- type ListFilter
- type Option
- func BaseURL(uri string) Option
- func Debug(logger DebugLogger) Option
- func DialTimeout(timeout time.Duration) Option
- func Handler(h http.Handler) Option
- func JSONMarshalOptions(opts ...json.Options) Option
- func JSONOptions(opts ...json.Options) Option
- func JSONUnmarshalOptions(opts ...json.Options) Option
- func OAuth2(src oauth2.TokenSource) Option
- func PersistentRequestOptions(reqOpts ...RequestOption) Option
- func RateLimit(requestsPerSecond int) Option
- func RateLimitFor(key string, requestsPerSecond int) Option
- func RateLimitForPerMinute(key string, requestsPerMinute int) Option
- func RateLimitPerMinute(requestsPerMinute int) Option
- func RateLimiter(l Limiter) Option
- func RateLimiterFor(key string, l Limiter) Option
- func RedactHeaders(names ...string) Option
- func RedactQueryParams(keys ...string) Option
- func Retry(policy RetryPolicy) Option
- func Timeout(timeout time.Duration) Option
- func Transport(rt http.RoundTripper) Option
- type Page
- type PageOptions
- type PlainText
- type RequestHandler
- type RequestOption
- func ClientTrace(clientTrace *httptrace.ClientTrace) RequestOption
- func ListMethod(method string) RequestOption
- func PageSize(size int) RequestOption
- func RequestAuthorization(value string) RequestOption
- func RequestAuthorizationBearer(accessToken string) RequestOption
- func RequestHeader(overridePrev bool, key string, values ...string) RequestOption
- func RequestParam(key string, values ...string) RequestOption
- func RequestQuery(query url.Values) RequestOption
- func RequestRateLimit(key string) RequestOption
- type RetryPolicy
- type Uploader
Constants ¶
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 ¶
var ErrUploaderClosed = httpclient.ErrUploaderClosed
ErrUploaderClosed is returned when an Uploader is used for a second upload.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ExtractError returns the response wrapped inside an APIError, reading and closing its body. A nil response yields the zero APIError.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
JSONMarshalOptions replaces the options used to encode request payloads (default jsonutil.DefaultMarshalOptions), leaving decoding alone.
func JSONOptions ¶
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 ¶
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 ¶
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 ¶
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 ¶
RateLimitForPerMinute is RateLimitFor expressed per minute.
func RateLimitPerMinute ¶
RateLimitPerMinute is RateLimit expressed per minute, with a burst of the whole minute's worth.
func RateLimiter ¶
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 ¶
RateLimiterFor registers a Limiter you own under a name. Nil removes it.
func RedactHeaders ¶
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 ¶
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 ¶
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.