Documentation
¶
Overview ¶
Package client is a thin HTTP client on top of net/http with base url, shared headers/cookies/query params, middlewares and a retry mechanism.
Connections ¶
Requests without an explicitly provided http.Client use the package level shared client (see DefaultHTTPClient) with a tuned connection pool, so TCP connections and TLS sessions are reused between calls. Never build an http.Client (and therefore an http.Transport) per request: transport owns the pool, so a per request transport means a new TCP connection plus a full TLS handshake for every call and idle connections which nobody closes.
Pool can be tuned per client:
c := client.New().
WithBaseURL("https://api.example.com").
WithConnectionPool(client.PoolConfig{MaxIdleConnsPerHost: 512})
Retries, timeouts, results ¶
RetryPolicy (Client.WithRetryPolicy) retries transport errors and the statuses 429/502/503/504 with backoff and Retry-After; without it the old WithRetryCount/WithRetryWait work. WithTimeout limits the whole call, WithAttemptTimeout one attempt, the default transport waits for the response headers at most DefaultResponseHeaderTimeout. Response.JSON, Response.Err and Request.WithResult parse the response, WithMaxResponseSize limits its size, Raw sends a raw body and WithObserver sees every attempt.
TLS ¶
By default, server certificates are NOT verified (InsecureSkipVerify). The default is kept for compatibility with deployments that use self-signed certificates between services. Set PoolConfig.TLSClientConfig to enable verification for a client:
c := client.New().WithConnectionPool(client.PoolConfig{
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
})
Index ¶
- Constants
- Variables
- func DefaultBackoff(attempt int) time.Duration
- func DefaultHTTPClient() *http.Client
- func NewHTTPClient(cfg PoolConfig) *http.Client
- func NewTransport(cfg PoolConfig) *http.Transport
- type AfterMiddleware
- type Attempt
- type BeforeMiddleware
- type BytesWriter
- type Client
- func (client *Client) R(ctx context.Context) *Request
- func (client *Client) WithAfterMiddlewares(m ...AfterMiddleware) *Client
- func (client *Client) WithAttemptTimeout(timeout time.Duration) *Client
- func (client *Client) WithAuthorization(token string) *Client
- func (client *Client) WithBaseURL(baseURL string) *Client
- func (client *Client) WithBasicAuth(username, password string) *Client
- func (client *Client) WithBearerToken(token string) *Client
- func (client *Client) WithBeforeMiddlewares(m ...BeforeMiddleware) *Client
- func (client *Client) WithConnectionPool(cfg PoolConfig) *Client
- func (client *Client) WithContentType(contentType string) *Client
- func (client *Client) WithCookie(cookie *http.Cookie) *Client
- func (client *Client) WithCookies(cookies []*http.Cookie) *Client
- func (client *Client) WithHeader(key, value string) *Client
- func (client *Client) WithHeaders(headers map[string]string) *Client
- func (client *Client) WithHttpClient(httpClient http.Client) *Client
- func (client *Client) WithMaxResponseSize(n int64) *Client
- func (client *Client) WithObserver(fn func(ctx context.Context, a Attempt)) *Client
- func (client *Client) WithQueries(queries map[string]string) *Client
- func (client *Client) WithQuery(key, value string) *Client
- func (client *Client) WithQueryValues(values url.Values) *Client
- func (client *Client) WithRequestOptions(opts ...RequestOption) *Client
- func (client *Client) WithRetryCount(count int) *Client
- func (client *Client) WithRetryPolicy(p RetryPolicy) *Client
- func (client *Client) WithRetryWait(wait time.Duration) *Client
- func (client *Client) WithTimeout(timeout time.Duration) *Client
- func (client *Client) WithTransport(rt http.RoundTripper) *Client
- type FormDataWriter
- type FormUrlEncodedWriter
- type HTTPError
- type Observer
- type PoolConfig
- type RawBody
- type Request
- func (request *Request) DELETE(url string, body ...any) (*Response, error)
- func (request *Request) Do(method, url string, body ...any) (*Response, error)
- func (request *Request) GET(url string, body ...any) (*Response, error)
- func (request *Request) HEAD(url string, body ...any) (*Response, error)
- func (request *Request) OPTIONS(url string, body ...any) (*Response, error)
- func (request *Request) PATCH(url string, body ...any) (*Response, error)
- func (request *Request) POST(url string, body ...any) (*Response, error)
- func (request *Request) PUT(url string, body ...any) (*Response, error)
- func (request *Request) WithAfterMiddleware(m ...AfterMiddleware) *Request
- func (request *Request) WithAttemptTimeout(timeout time.Duration) *Request
- func (request *Request) WithAuthorization(token string) *Request
- func (request *Request) WithBasicAuth(username, password string) *Request
- func (request *Request) WithBearerToken(token string) *Request
- func (request *Request) WithBeforeMiddleware(m ...BeforeMiddleware) *Request
- func (request *Request) WithContentType(contentType string) *Request
- func (request *Request) WithCookie(cookie *http.Cookie) *Request
- func (request *Request) WithCookies(cookies []*http.Cookie) *Request
- func (request *Request) WithHeader(key, value string) *Request
- func (request *Request) WithHeaders(headers map[string]string) *Request
- func (request *Request) WithHttpClient(client *http.Client) *Request
- func (request *Request) WithMaxResponseSize(n int64) *Request
- func (request *Request) WithObserver(fn func(ctx context.Context, a Attempt)) *Request
- func (request *Request) WithQueries(queries map[string]string) *Request
- func (request *Request) WithQuery(key, value string) *Request
- func (request *Request) WithQueryValues(values url.Values) *Request
- func (request *Request) WithRequestOptions(opts ...RequestOption) *Request
- func (request *Request) WithResult(v any) *Request
- func (request *Request) WithRetryCount(count int) *Request
- func (request *Request) WithRetryPolicy(p RetryPolicy) *Request
- func (request *Request) WithRetryWait(wait time.Duration) *Request
- func (request *Request) WithTimeout(timeout time.Duration) *Request
- type RequestOption
- type Response
- func (response *Response) BodyRaw() []byte
- func (response *Response) ContentType() string
- func (response *Response) Context(ctx context.Context) context.Contextdeprecated
- func (response *Response) Err() error
- func (response *Response) IsFailure() bool
- func (response *Response) JSON(v any) error
- func (response *Response) Raw() *http.Response
- func (response *Response) RequestURL() string
- func (response *Response) Status() string
- func (response *Response) StatusCode() int
- type RetryPolicy
Examples ¶
Constants ¶
const ( // DefaultRetryMaxAttempts is the total number of attempts (the first one // included) when RetryPolicy.MaxAttempts is not set. DefaultRetryMaxAttempts = 3 // DefaultBackoffBase is the delay after the first failed attempt in // DefaultBackoff; every next attempt doubles it. DefaultBackoffBase = 100 * time.Millisecond // DefaultBackoffMax is the upper bound of DefaultBackoff (before jitter). DefaultBackoffMax = 5 * time.Second )
Defaults of RetryPolicy. They are used for the zero fields of the policy.
const ( // DefaultMaxIdleConns is a total limit of kept idle connections. DefaultMaxIdleConns = 256 // DefaultMaxIdleConnsPerHost is a per-host limit of kept idle connections. // // net/http default is 2 which throttles parallel calls to the same host: // every extra parallel call opens a connection which is closed right after // the response instead of being reused. DefaultMaxIdleConnsPerHost = 128 // DefaultMaxConnsPerHost is a per-host limit of total connections. // Zero means no limit. DefaultMaxConnsPerHost = 0 // DefaultIdleConnTimeout is how long an idle connection is kept in the pool. DefaultIdleConnTimeout = 90 * time.Second // DefaultTLSHandshakeTimeout limits TLS handshake duration. DefaultTLSHandshakeTimeout = 5 * time.Second // DefaultExpectContinueTimeout limits wait for the first response headers // after "Expect: 100-continue" request header was sent. DefaultExpectContinueTimeout = time.Second // DefaultDialTimeout limits establishing of a TCP connection. DefaultDialTimeout = 3 * time.Second // DefaultDialKeepAlive is a TCP keep-alive probe interval. DefaultDialKeepAlive = 30 * time.Second // DefaultResponseHeaderTimeout limits the wait for the response headers // after the request was fully written. // // Without it a hung connection blocks the call forever if the call has // no WithTimeout. 60 seconds because some services answer with the headers // only after the whole response is built, so a shorter value is not safe. // The time of reading the body is not limited by it. DefaultResponseHeaderTimeout = 60 * time.Second )
Default connection pool settings used by the package level http.Client.
They are tuned for service-to-service calls: connections are kept alive and reused between requests, idle connections are dropped after IdleConnTimeout so neither file descriptors nor readLoop/writeLoop goroutines can pile up.
const HTTPErrorBodyLimit = 1024
HTTPErrorBodyLimit is the max length of HTTPError.Body.
Variables ¶
var ( // ErrParseResponseBody wraps JSON decoding errors of Response.JSON and // Request.WithResult. ErrParseResponseBody = errors.New("response.parse_body") // ErrExportResponseMustBePointer is not returned by the library. // // Deprecated: not returned by the library; do not use. ErrExportResponseMustBePointer = errors.New("response.export_must_be_pointer") // ErrBytesWriterWrite wraps write errors of BytesWriter. ErrBytesWriterWrite = errors.New("bytes_writer.write") // ErrFormDataWriterAdd wraps errors of FormDataWriter.Add. ErrFormDataWriterAdd = errors.New("formdata_writer.add") // ErrFormDataWriterAddFile wraps errors of FormDataWriter.AddFile. ErrFormDataWriterAddFile = errors.New("formdata_writer.add_file") // ErrFormDataWriterSet wraps errors of FormDataWriter.Set. ErrFormDataWriterSet = errors.New("formdata_writer.set") // ErrFormDataWriterClose wraps errors of FormDataWriter.Close. ErrFormDataWriterClose = errors.New("formdata_writer.close") // ErrResponseTooLarge is returned when the response body is bigger than // the limit of WithMaxResponseSize. It is not retried. ErrResponseTooLarge = errors.New("response.too_large") // ErrRawBodyUnsupported is returned when Raw got a body which is neither // []byte nor io.Reader. ErrRawBodyUnsupported = errors.New("raw.unsupported_body") // ErrRequestRetryDo wraps (errors.Join) the errors of all failed attempts. ErrRequestRetryDo = errors.New("request.retry_do") // ErrRequestRewindBody is returned when the request body cannot be // replayed for a retry. ErrRequestRewindBody = errors.New("request.rewind_body") )
Sentinel errors of the package; match them with errors.Is.
Functions ¶
func DefaultBackoff ¶
DefaultBackoff is the default RetryPolicy.Backoff: the delay doubles on every attempt starting from DefaultBackoffBase up to DefaultBackoffMax, half of it is a random jitter.
func DefaultHTTPClient ¶
DefaultHTTPClient returns the package level http.Client which is used by every Request without an explicitly provided client.
The client is created once (lazily) and shared, so connections are reused between requests, services and goroutines. It has no http.Client.Timeout: deadlines are controlled by the request context (see Client.WithTimeout). The transport waits for the response headers at most DefaultResponseHeaderTimeout.
Returned client is shared - do not mutate it. Use Client.WithHttpClient, Client.WithTransport or Client.WithConnectionPool to get an own one.
func NewHTTPClient ¶
func NewHTTPClient(cfg PoolConfig) *http.Client
NewHTTPClient creates http.Client with own connection pool described by cfg.
Every created client holds its own pool, so it must be created once and reused - do not call it per request.
func NewTransport ¶
func NewTransport(cfg PoolConfig) *http.Transport
NewTransport creates http.Transport with a connection pool described by cfg. Zero fields of cfg are replaced with package defaults.
TLS: if cfg.TLSClientConfig is nil the transport skips certificate verification (InsecureSkipVerify: true).
This default is kept for backward compatibility with deployments that talk to services behind self-signed certificates. Set PoolConfig.TLSClientConfig (for example &tls.Config{} or one with your RootCAs) to enable verification.
Types ¶
type AfterMiddleware ¶
AfterMiddleware is called after every attempt that received and read a response. It does not see transport errors; use an Observer for them.
type Attempt ¶
type Attempt struct {
// Method and URL of the request.
Method string
URL string
// Attempt is the number of the attempt, starting from 1.
Attempt int
// StatusCode is the status of the response, 0 if there is no response.
StatusCode int
// Err is a transport error, the timeout of the attempt or an error of
// reading/parsing the response body; nil if the response is received
// and read successfully.
Err error
// Duration is the time from sending the request to the end of reading
// the response body.
Duration time.Duration
}
Attempt describes one attempt (one sent http request) of a call.
type BeforeMiddleware ¶
BeforeMiddleware is called before every attempt with the method and the URL passed to the call (without the base URL).
type BytesWriter ¶
type BytesWriter interface {
io.Writer
ContentType() string
Bytes() []byte
SetContentType(contentType string) BytesWriter
Reader() io.Reader
}
BytesWriter is a request body made of arbitrary bytes. Pass it as the body of a call and it is sent as is with its ContentType.
The default content type is "application/octet-stream"; change it with SetContentType. For a one-off raw body see also Raw.
func NewBytesWriter ¶
func NewBytesWriter() BytesWriter
NewBytesWriter creates an empty BytesWriter.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client holds settings shared by the requests it creates: base URL, headers, cookies, query params, auth, timeouts, retry policy, middlewares and observers. Create a Request with Client.R.
Configure a Client once and reuse it; the With* methods mutate the Client and are not safe to call concurrently with R.
func New ¶
func New() *Client
New creates a Client.
New is cheap and safe to call per request ONLY as long as the Client uses the shared package level transport (see DefaultHTTPClient) - the connection pool is not owned by the Client then. Options which create or plug in an own transport (WithConnectionPool, WithTransport, WithHttpClient) make the pool belong to that Client: such a Client must be created once and reused, otherwise every call gets a pool of its own (a new TCP connection plus a TLS handshake and idle connections which nobody closes).
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/boostgo/httpkit/client"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"id":%q,"auth":%q}`, r.URL.Query().Get("id"), r.Header.Get("Authorization"))
}))
defer srv.Close()
c := client.New().
WithBaseURL(srv.URL).
WithBearerToken("secret").
WithTimeout(5 * time.Second)
var user struct {
ID string `json:"id"`
Auth string `json:"auth"`
}
resp, err := c.R(context.Background()).
WithQuery("id", "42").
WithResult(&user).
GET("/users")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(resp.StatusCode(), user.ID, user.Auth)
}
Output: 200 42 Bearer secret
func (*Client) WithAfterMiddlewares ¶
func (client *Client) WithAfterMiddlewares(m ...AfterMiddleware) *Client
WithAfterMiddlewares adds middlewares called after every successful attempt (a response was received and read) of every nested request. Transport errors are not passed to them; use WithObserver for that.
func (*Client) WithAttemptTimeout ¶
WithAttemptTimeout sets the timeout of one attempt for every nested request, see Request.WithAttemptTimeout.
func (*Client) WithAuthorization ¶
WithAuthorization sets authorization token for "Authorization" header.
Prefix "Bearer " will set automatically
func (*Client) WithBaseURL ¶
WithBaseURL sets base url for every nested requests
func (*Client) WithBasicAuth ¶
WithBasicAuth sets username & password for basic auth mechanism
func (*Client) WithBearerToken ¶
WithBearerToken sets token for "Authorization" header.
Prefix "Bearer " sets automatically.
func (*Client) WithBeforeMiddlewares ¶
func (client *Client) WithBeforeMiddlewares(m ...BeforeMiddleware) *Client
WithBeforeMiddlewares adds middlewares called before every attempt of every nested request.
func (*Client) WithConnectionPool ¶
func (client *Client) WithConnectionPool(cfg PoolConfig) *Client
WithConnectionPool sets own connection pool for every nested request.
Zero fields of the cfg are replaced with package defaults, so it is enough to set only what has to be changed:
client.New().WithConnectionPool(client.PoolConfig{MaxIdleConnsPerHost: 512})
Without this option requests use the shared package level client (see DefaultHTTPClient) which already reuses connections.
The pool belongs to this Client: create the Client once and reuse it, not per request - otherwise every call gets a pool of its own.
func (*Client) WithContentType ¶
WithContentType sets header value to "Content-Type" header.
func (*Client) WithCookies ¶
WithCookies sets new cookies map to request.
Existing keys will be rewritten
func (*Client) WithHeader ¶
WithHeader set one more key-value pair to headers.
If key already exist it rewrites existing key value
func (*Client) WithHeaders ¶
WithHeaders sets map of key-value pairs.
Existing keys will be rewritten
func (*Client) WithHttpClient ¶
WithHttpClient set default http client for every nested request.
Provided client has the highest priority: it is used as is, instead of the shared package level client. Create it once and reuse the Client - a client created per request means a connection pool per request (no keep-alive). Its transport is used as is: the package defaults (for example DefaultResponseHeaderTimeout) do not apply to it.
func (*Client) WithMaxResponseSize ¶
WithMaxResponseSize limits the size of the response body of every nested request to n bytes, see Request.WithMaxResponseSize. n <= 0 means no limit (default).
func (*Client) WithObserver ¶
WithObserver adds an observer which is called after every attempt of every nested request, including transport errors, see Observer. The observers added on a Request are called after the ones of the Client.
func (*Client) WithQueries ¶
WithQueries sets query params to request.
Existing keys will be rewritten
func (*Client) WithQueryValues ¶
WithQueryValues adds query params with several values per key to nested requests: "id": {"1", "2"} gives "?id=1&id=2". See Request.WithQueryValues.
func (*Client) WithRequestOptions ¶
func (client *Client) WithRequestOptions(opts ...RequestOption) *Client
WithRequestOptions sets option functions which can modify created request.
func (*Client) WithRetryCount ¶
WithRetryCount sets count of retries need.
By default, retry count is 1
func (*Client) WithRetryPolicy ¶
func (client *Client) WithRetryPolicy(p RetryPolicy) *Client
WithRetryPolicy sets the retry policy for every nested request, see RetryPolicy. A policy set on a Request overrides it.
Example ¶
c := client.New().
WithBaseURL("http://users.example").
WithTransport(fakeServer()).
WithRetryPolicy(client.RetryPolicy{
MaxAttempts: 3,
Backoff: func(int) time.Duration { return time.Millisecond },
}).
WithObserver(func(_ context.Context, a client.Attempt) {
fmt.Printf("attempt %d: status %d\n", a.Attempt, a.StatusCode)
})
// GET is retried on 503; a POST would need RetryPolicy.RetryNonIdempotent
resp, err := c.R(context.Background()).GET("/users/42")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(resp.StatusCode(), string(resp.BodyRaw()))
Output: attempt 1: status 503 attempt 2: status 200 200 {"name":"user-42"}
func (*Client) WithRetryWait ¶
WithRetryWait sets wait time between retry requests.
Default wait time is 100ms.
func (*Client) WithTimeout ¶
WithTimeout sets timeout for waiting for request.
By default, there is no timeout
func (*Client) WithTransport ¶
func (client *Client) WithTransport(rt http.RoundTripper) *Client
WithTransport sets custom http.RoundTripper for every nested request.
It builds an own http.Client on top of the transport, so the package level shared client (and its connection pool) is not affected. The pool belongs to this Client: create the Client once and reuse it, not per request. The transport is used as is, the package defaults (for example DefaultResponseHeaderTimeout) do not apply to it.
Nil transport is ignored.
type FormDataWriter ¶
type FormDataWriter interface {
// Add writes a text field.
Add(key, value string) error
// AddFile writes a file field with the given file name and content.
AddFile(name, fileName string, file []byte) error
// Set writes every pair of data as a text field.
Set(data map[string]string) error
// Boundary returns the multipart boundary.
Boundary() string
// ContentType returns the multipart Content-Type with the boundary.
ContentType() string
// Buffer returns the encoded body.
Buffer() *bytes.Buffer
// Close writes the trailing boundary. It is called by the client before
// sending.
Close() error
}
FormDataWriter is a multipart/form-data request body. Pass it as the body of a call: it is closed and sent with the multipart Content-Type (including the boundary) automatically.
func NewFormData ¶
func NewFormData() FormDataWriter
NewFormData creates an empty FormDataWriter.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/boostgo/httpkit/client"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(1 << 20); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, header, _ := r.FormFile("avatar")
_, _ = fmt.Fprintf(w, "%s %s %d", r.FormValue("name"), header.Filename, header.Size)
}))
defer srv.Close()
form := client.NewFormData()
_ = form.Add("name", "alice")
_ = form.AddFile("avatar", "alice.png", []byte("PNG..."))
resp, err := client.New().WithBaseURL(srv.URL).R(context.Background()).POST("/upload", form)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(resp.BodyRaw()))
}
Output: alice alice.png 6
type FormUrlEncodedWriter ¶
type FormUrlEncodedWriter interface {
// Set sets the value of key, replacing existing values.
Set(key, value string)
// Get returns the first value of key.
Get(key string) string
// Delete removes key.
Delete(key string)
// Has reports whether key is set.
Has(key string) bool
// Reader returns the encoded form.
Reader() io.Reader
}
FormUrlEncodedWriter is an application/x-www-form-urlencoded request body. Pass it as the body of a call; the Content-Type is set automatically.
func NewFormUrlEncodedWriter ¶
func NewFormUrlEncodedWriter() FormUrlEncodedWriter
NewFormUrlEncodedWriter creates an empty FormUrlEncodedWriter.
type HTTPError ¶
type HTTPError struct {
StatusCode int
Method string
URL string
// Body is the beginning of the response body, not longer than
// HTTPErrorBodyLimit bytes.
Body []byte
}
HTTPError is the error for a response with a non-2xx status, see Response.Err.
type Observer ¶
Observer is called after every attempt of a call, including the attempts which failed with a transport error. See Client.WithObserver.
type PoolConfig ¶
type PoolConfig struct {
// MaxIdleConns is a total limit of kept idle connections.
// Default is DefaultMaxIdleConns.
MaxIdleConns int
// MaxIdleConnsPerHost is a per-host limit of kept idle connections.
// Default is DefaultMaxIdleConnsPerHost.
MaxIdleConnsPerHost int
// MaxConnsPerHost is a per-host limit of total connections
// (active + idle). Default is DefaultMaxConnsPerHost (no limit).
//
// Negative value also means no limit, it allows to reset the field
// explicitly when defaults change.
MaxConnsPerHost int
// IdleConnTimeout is how long an idle connection is kept in the pool.
// Default is DefaultIdleConnTimeout.
//
// Zero value of the raw http.Transport means "keep forever" which leaks
// sockets and goroutines, so here zero is replaced with the default.
IdleConnTimeout time.Duration
// TLSHandshakeTimeout limits TLS handshake duration.
// Default is DefaultTLSHandshakeTimeout.
TLSHandshakeTimeout time.Duration
// ExpectContinueTimeout limits wait for the first response headers after
// "Expect: 100-continue" request header was sent.
// Default is DefaultExpectContinueTimeout.
ExpectContinueTimeout time.Duration
// DialTimeout limits establishing of a TCP connection.
// Default is DefaultDialTimeout.
DialTimeout time.Duration
// DialKeepAlive is a TCP keep-alive probe interval.
// Default is DefaultDialKeepAlive.
DialKeepAlive time.Duration
// ResponseHeaderTimeout limits the wait for the response headers after the
// request was fully written; expiration is a transport error (retried by
// RetryPolicy). Default is DefaultResponseHeaderTimeout.
//
// Negative value means no timeout (the behaviour before the default
// appeared), like MaxConnsPerHost it allows to reset the field explicitly.
ResponseHeaderTimeout time.Duration
// DisableHTTP2 turns off automatic HTTP/2 negotiation.
// By default, HTTP/2 is attempted (ForceAttemptHTTP2 is true).
DisableHTTP2 bool
// TLSClientConfig overrides TLS settings of the transport.
//
// If it is nil - certificate verification stays disabled to keep
// historical behaviour of the library, see NewTransport.
TLSClientConfig *tls.Config
}
PoolConfig describes connection pool of an http.Transport.
Zero value of every field means "use default", so it is safe to set only fields which have to be changed:
c := client.New().WithConnectionPool(client.PoolConfig{
MaxIdleConnsPerHost: 512,
})
func DefaultPoolConfig ¶
func DefaultPoolConfig() PoolConfig
DefaultPoolConfig returns connection pool settings used by default.
type RawBody ¶
type RawBody struct {
// contains filtered or unexported fields
}
RawBody is a request body which is sent as is, see Raw.
func Raw ¶
Raw makes an explicit raw request body: the bytes are sent as is, without JSON, with the given Content-Type (empty means application/octet-stream).
c.R(ctx).POST("/upload", client.Raw(blob, "image/png"))
body is []byte or io.Reader (nil is an empty body); another type is an error of the call wrapping ErrRawBodyUnsupported. An io.Reader is read into memory once when the request is built, so the body survives retries; a reader cannot be reused for the next call. A []byte without Raw is still sent as a JSON (base64) string.
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/boostgo/httpkit/client"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
_, _ = fmt.Fprintf(w, "%s %s", r.Header.Get("Content-Type"), body)
}))
defer srv.Close()
resp, err := client.New().WithBaseURL(srv.URL).R(context.Background()).
POST("/raw", client.Raw([]byte("hello"), "text/plain"))
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(resp.BodyRaw()))
}
Output: text/plain hello
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request is one HTTP call (with its retries) being configured. Create it with R or Client.R, set options with the With* methods and finish with Do, GET, POST, PUT, PATCH, DELETE, OPTIONS or HEAD.
A Request may be reused for several calls; calls on one Request are serialized.
func R ¶
R creates a standalone Request (without a Client) bound to ctx; a nil ctx means context.Background().
func (*Request) DELETE ¶
DELETE execute request with method "DELETE" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) Do ¶
Do execute request with the provided method and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) GET ¶
GET execute request with method "GET" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) HEAD ¶
HEAD execute request with method "HEAD" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) OPTIONS ¶
OPTIONS execute request with method "OPTIONS" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) PATCH ¶
PATCH execute request with method "PATCH" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) POST ¶
POST execute request with method "POST" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) PUT ¶
PUT execute request with method "PUT" and returns Response object.
url - if base url set concat baseURL + url.
body - request body. If provide body as FormDataWriter interface - will be used form-data body. Optional
func (*Request) WithAfterMiddleware ¶
func (request *Request) WithAfterMiddleware(m ...AfterMiddleware) *Request
WithAfterMiddleware adds middlewares called after every attempt that received and read a response.
func (*Request) WithAttemptTimeout ¶
WithAttemptTimeout sets the timeout of one attempt (inside the total WithTimeout of the call). The context of the attempt lives until the response body is read. The timeout is a transport error and is retried by RetryPolicy.
By default, there is no timeout of an attempt
func (*Request) WithAuthorization ¶
WithAuthorization sets authorization token for "Authorization" header.
Prefix "Bearer " will set automatically
func (*Request) WithBasicAuth ¶
WithBasicAuth sets username & password for basic auth mechanism
func (*Request) WithBearerToken ¶
WithBearerToken sets token for "Authorization" header.
Prefix "Bearer " sets automatically
func (*Request) WithBeforeMiddleware ¶
func (request *Request) WithBeforeMiddleware(m ...BeforeMiddleware) *Request
WithBeforeMiddleware adds middlewares called before every attempt.
func (*Request) WithContentType ¶
WithContentType sets header value to "Content-Type" header.
func (*Request) WithCookies ¶
WithCookies sets new cookies map to request.
Existing keys will be rewritten
func (*Request) WithHeader ¶
WithHeader set one more key-value pair to headers.
If key already exist it rewrites existing key value
func (*Request) WithHeaders ¶
WithHeaders sets map of key-value pairs.
Existing keys will be rewritten
func (*Request) WithHttpClient ¶
WithHttpClient set default http client for current Request object.
func (*Request) WithMaxResponseSize ¶
WithMaxResponseSize limits the size of the response body to n bytes; a bigger response is an error of the call wrapping ErrResponseTooLarge (not retried). n <= 0 means no limit (default).
Content-Length bigger than n fails the call at once, without reading the body. It works for the whole-body read and for WithResult with a 2xx status. For a non-2xx status with WithResult only the first min(n, 64 KiB) bytes are kept in BodyRaw and the rest is dropped without an error, so the status stays available.
func (*Request) WithObserver ¶
WithObserver adds an observer which is called after every attempt of the call, including transport errors and timeouts of an attempt (Attempt.Err), see Observer. The observers of the Request are called after the ones of the Client. The old Before/After middlewares work as before.
func (*Request) WithQueries ¶
WithQueries sets query params to request.
Existing keys will be rewritten
func (*Request) WithQueryValues ¶
WithQueryValues adds query params with several values per key: "id": {"1", "2"} gives "?id=1&id=2".
The values are added (url.Values.Add) after the params of WithQuery/WithQueries (which set one value per key) and after the values already added.
func (*Request) WithRequestOptions ¶
func (request *Request) WithRequestOptions(opts ...RequestOption) *Request
WithRequestOptions sets option functions which can modify created request.
func (*Request) WithResult ¶
WithResult decodes a 2xx response body as JSON straight from the connection into v, without reading it into a []byte first: BodyRaw is empty.
A decode error is an error of the call and wraps ErrParseResponseBody. An empty body (for example 204) leaves v untouched and is not an error.
For a non-2xx status v is not touched, the call does not fail, the first 64 KiB of the body are available in BodyRaw and Response.Err returns *HTTPError.
In both cases the rest of the body is read and closed, so the connection returns to the pool. Without WithResult the whole body is read into BodyRaw.
Example ¶
c := client.New().
WithBaseURL("http://users.example").
WithTransport(fakeServer())
var user struct {
Name string `json:"name"`
}
// the first answer is 503: no error of the call, the status is in resp.Err
resp, err := c.R(context.Background()).WithResult(&user).GET("/users/42")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(resp.Err())
// the second one is decoded straight from the connection into user
if _, err = c.R(context.Background()).WithResult(&user).GET("/users/42"); err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(user.Name)
Output: GET http://users.example/users/42: status 503: {"error":"busy"} user-42
func (*Request) WithRetryCount ¶
WithRetryCount sets count of retries need.
By default, retry count is 1
func (*Request) WithRetryPolicy ¶
func (request *Request) WithRetryPolicy(p RetryPolicy) *Request
WithRetryPolicy sets the retry policy of the call, see RetryPolicy.
The policy overrides the one inherited from the Client and has priority over WithRetryCount/WithRetryWait.
func (*Request) WithRetryWait ¶
WithRetryWait sets wait time between retry requests.
Default wait time is 100ms
type RequestOption ¶
RequestOption modifies the built *http.Request right before it is sent (after headers, cookies and auth were applied).
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response is the result of a call: the status, headers and the read body. The underlying body is always fully read and closed by the client.
func (*Response) BodyRaw ¶
BodyRaw returns the response body. It is empty for a 2xx response of a call made with Request.WithResult.
func (*Response) ContentType ¶
ContentType returns the Content-Type header of the response.
func (*Response) Err ¶
Err returns nil for a 2xx response, otherwise *HTTPError (use errors.As) with the first HTTPErrorBodyLimit bytes of the body.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/boostgo/httpkit/client"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "no such user", http.StatusNotFound)
}))
defer srv.Close()
resp, err := client.New().WithBaseURL(srv.URL).R(context.Background()).GET("/users/7")
if err != nil {
fmt.Println("transport error:", err)
return
}
var httpErr *client.HTTPError
if errors.As(resp.Err(), &httpErr) {
fmt.Println(httpErr.StatusCode, strings.TrimSpace(string(httpErr.Body)))
}
}
Output: 404 no such user
func (*Response) JSON ¶
JSON decodes the response body (BodyRaw) into v.
The error wraps ErrParseResponseBody. The body is empty if the call was made with Request.WithResult, use that v instead.
func (*Response) Raw ¶
Raw returns the underlying *http.Response. Its Body is already consumed; use BodyRaw.
func (*Response) RequestURL ¶
RequestURL returns the full URL (with base URL and query) of the request which produced this response. After redirects it is the URL of the last one.
func (*Response) StatusCode ¶
StatusCode returns the HTTP status code.
type RetryPolicy ¶
type RetryPolicy struct {
// MaxAttempts is the total number of attempts, the first one included.
// Zero or negative means DefaultRetryMaxAttempts.
MaxAttempts int
// Backoff returns the delay before the next attempt; attempt is the
// number (from 1) of the attempt which has just failed.
// Nil means DefaultBackoff (exponential with jitter).
//
// For the responses 429 and 503 the Retry-After header (seconds or
// HTTP-date) is respected: the call waits at least that long. The wait
// is bounded only by the context (WithTimeout or the one passed to R).
Backoff func(attempt int) time.Duration
// RetryOn tells if the attempt has to be retried: resp is nil if there is
// no response (transport error), err is nil if a response is received.
// Nil means: transport error or status 429/502/503/504, and only for
// idempotent methods unless RetryNonIdempotent is set.
//
// A custom RetryOn decides completely by itself, RetryNonIdempotent is not
// applied to it (resp.Raw().Request.Method is available if resp != nil).
RetryOn func(resp *Response, err error) bool
// RetryNonIdempotent allows the default RetryOn to retry POST and PATCH.
// Retrying them can duplicate the effect on the server.
RetryNonIdempotent bool
}
RetryPolicy describes when and how a call is retried. Zero fields are replaced with defaults.
Without a policy the old mechanism (WithRetryCount, WithRetryWait) works: any error of the call is retried, for any method, statuses are not retried. If both a policy and WithRetryCount are set the policy wins and WithRetryCount/WithRetryWait are ignored. A policy set on a Request overrides the one inherited from the Client.
By default a call is retried on a transport error (including the timeout of one attempt, see WithAttemptTimeout) and on the statuses 429, 502, 503 and 504. Only idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS) are retried; POST and PATCH are retried only if RetryNonIdempotent is set.
If the last attempt returned a response (for example 503) the call returns this *Response and a nil error. If the attempts are over with an error the call returns ErrRequestRetryDo wrapping (errors.Join) the errors of the attempts. Waiting between attempts is interrupted by the context.