Documentation
¶
Overview ¶
Package httpclient sends HTTP requests and decodes responses into Go values.
Index ¶
- func Delete[T any](client *Client, url string, opts ...Option) (T, error)
- func DeleteCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error)
- func Do[T any](r *req.Request) (T, *req.Response, error)
- func Dump(values ...any)
- func Get[T any](client *Client, url string, opts ...Option) (T, error)
- func GetCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error)
- func Head[T any](client *Client, url string, opts ...Option) (T, error)
- func HeadCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error)
- func Options[T any](client *Client, url string, opts ...Option) (T, error)
- func OptionsCtx[T any](client *Client, ctx context.Context, url string, opts ...Option) (T, error)
- func Patch[In any, Out any](client *Client, url string, body In, opts ...Option) (Out, error)
- func PatchCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error)
- func Post[In any, Out any](client *Client, url string, body In, opts ...Option) (Out, error)
- func PostCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error)
- func Put[In any, Out any](client *Client, url string, body In, opts ...Option) (Out, error)
- func PutCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error)
- type Client
- func (c *Client) Delete[Out any](url string, opts ...Option) (Out, error)
- func (c *Client) DeleteCtx[Out any](ctx context.Context, url string, opts ...Option) (Out, error)
- func (c *Client) Get[Out any](url string, opts ...Option) (Out, error)
- func (c *Client) GetCtx[Out any](ctx context.Context, url string, opts ...Option) (Out, error)
- func (c *Client) Head[Out any](url string, opts ...Option) (Out, error)
- func (c *Client) HeadCtx[Out any](ctx context.Context, url string, opts ...Option) (Out, error)
- func (c *Client) Options[Out any](url string, opts ...Option) (Out, error)
- func (c *Client) OptionsCtx[Out any](ctx context.Context, url string, opts ...Option) (Out, error)
- func (c *Client) Patch[Out any](url string, body any, opts ...Option) (Out, error)
- func (c *Client) PatchCtx[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)
- func (c *Client) Post[Out any](url string, body any, opts ...Option) (Out, error)
- func (c *Client) PostCtx[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)
- func (c *Client) Put[Out any](url string, body any, opts ...Option) (Out, error)
- func (c *Client) PutCtx[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)
- func (c *Client) Raw() *req.Client
- func (c *Client) Req() *req.Client
- type ErrorMapperFunc
- type HTTPError
- type Option
- type OptionBuilder
- func AsChrome() OptionBuilder
- func AsFirefox() OptionBuilder
- func AsMobile() OptionBuilder
- func AsSafari() OptionBuilder
- func Auth(scheme, token string) OptionBuilder
- func BaseURL(url string) OptionBuilder
- func Basic(user, pass string) OptionBuilder
- func Bearer(token string) OptionBuilder
- func Before(fn func(*req.Request)) OptionBuilder
- func Body(value any) OptionBuilder
- func CookieJar(jar http.CookieJar) OptionBuilder
- func DumpAll() OptionBuilder
- func DumpEachRequest() OptionBuilder
- func DumpEachRequestTo(output io.Writer) OptionBuilder
- func DumpTo(output io.Writer) OptionBuilder
- func DumpToFile(filename string) OptionBuilder
- func EnableDump() OptionBuilder
- func ErrorMapper(fn ErrorMapperFunc) OptionBuilder
- func File(paramName, filePath string) OptionBuilder
- func FileBytes(paramName, filename string, content []byte) OptionBuilder
- func FileReader(paramName, filename string, reader io.Reader) OptionBuilder
- func Files(files map[string]string) OptionBuilder
- func Form(values map[string]string) OptionBuilder
- func Header(key, value string) OptionBuilder
- func Headers(values map[string]string) OptionBuilder
- func JSON(value any) OptionBuilder
- func Middleware(mw ...req.RequestMiddleware) OptionBuilder
- func OutputFile(path string) OptionBuilder
- func Path(key string, value any) OptionBuilder
- func Paths(values map[string]any) OptionBuilder
- func Proxy(proxyURL string) OptionBuilder
- func ProxyFunc(fn func(*http.Request) (*url.URL, error)) OptionBuilder
- func Queries(values map[string]string) OptionBuilder
- func Query(kv ...string) OptionBuilder
- func Redirect(policies ...req.RedirectPolicy) OptionBuilder
- func Retry(fn func(*req.Client)) OptionBuilder
- func RetryBackoff(min, max time.Duration) OptionBuilder
- func RetryCondition(condition req.RetryConditionFunc) OptionBuilder
- func RetryCount(count int) OptionBuilder
- func RetryFixedInterval(interval time.Duration) OptionBuilder
- func RetryHook(hook req.RetryHookFunc) OptionBuilder
- func RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder
- func TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
- func TLSFingerprintAndroid() OptionBuilder
- func TLSFingerprintChrome() OptionBuilder
- func TLSFingerprintEdge() OptionBuilder
- func TLSFingerprintFirefox() OptionBuilder
- func TLSFingerprintIOS() OptionBuilder
- func TLSFingerprintRandomized() OptionBuilder
- func TLSFingerprintSafari() OptionBuilder
- func Timeout(d time.Duration) OptionBuilder
- func Trace() OptionBuilder
- func TraceAll() OptionBuilder
- func Transport(rt http.RoundTripper) OptionBuilder
- func UploadCallback(callback req.UploadCallback) OptionBuilder
- func UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder
- func UploadProgress() OptionBuilder
- func UserAgent(value string) OptionBuilder
- func (b OptionBuilder) AsChrome() OptionBuilder
- func (b OptionBuilder) AsFirefox() OptionBuilder
- func (b OptionBuilder) AsMobile() OptionBuilder
- func (b OptionBuilder) AsSafari() OptionBuilder
- func (b OptionBuilder) Auth(scheme, token string) OptionBuilder
- func (b OptionBuilder) BaseURL(url string) OptionBuilder
- func (b OptionBuilder) Basic(user, pass string) OptionBuilder
- func (b OptionBuilder) Bearer(token string) OptionBuilder
- func (b OptionBuilder) Before(fn func(*req.Request)) OptionBuilder
- func (b OptionBuilder) Body(value any) OptionBuilder
- func (b OptionBuilder) CookieJar(jar http.CookieJar) OptionBuilder
- func (b OptionBuilder) DumpAll() OptionBuilder
- func (b OptionBuilder) DumpEachRequest() OptionBuilder
- func (b OptionBuilder) DumpEachRequestTo(output io.Writer) OptionBuilder
- func (b OptionBuilder) DumpTo(output io.Writer) OptionBuilder
- func (b OptionBuilder) DumpToFile(filename string) OptionBuilder
- func (b OptionBuilder) EnableDump() OptionBuilder
- func (b OptionBuilder) ErrorMapper(fn ErrorMapperFunc) OptionBuilder
- func (b OptionBuilder) File(paramName, filePath string) OptionBuilder
- func (b OptionBuilder) FileBytes(paramName, filename string, content []byte) OptionBuilder
- func (b OptionBuilder) FileReader(paramName, filename string, reader io.Reader) OptionBuilder
- func (b OptionBuilder) Files(files map[string]string) OptionBuilder
- func (b OptionBuilder) Form(values map[string]string) OptionBuilder
- func (b OptionBuilder) Header(key, value string) OptionBuilder
- func (b OptionBuilder) Headers(values map[string]string) OptionBuilder
- func (b OptionBuilder) JSON(value any) OptionBuilder
- func (b OptionBuilder) Middleware(mw ...req.RequestMiddleware) OptionBuilder
- func (b OptionBuilder) OutputFile(path string) OptionBuilder
- func (b OptionBuilder) Path(key string, value any) OptionBuilder
- func (b OptionBuilder) Paths(values map[string]any) OptionBuilder
- func (b OptionBuilder) Proxy(proxyURL string) OptionBuilder
- func (b OptionBuilder) ProxyFunc(fn func(*http.Request) (*url.URL, error)) OptionBuilder
- func (b OptionBuilder) Queries(values map[string]string) OptionBuilder
- func (b OptionBuilder) Query(kv ...string) OptionBuilder
- func (b OptionBuilder) Redirect(policies ...req.RedirectPolicy) OptionBuilder
- func (b OptionBuilder) Retry(fn func(*req.Client)) OptionBuilder
- func (b OptionBuilder) RetryBackoff(min, max time.Duration) OptionBuilder
- func (b OptionBuilder) RetryCondition(condition req.RetryConditionFunc) OptionBuilder
- func (b OptionBuilder) RetryCount(count int) OptionBuilder
- func (b OptionBuilder) RetryFixedInterval(interval time.Duration) OptionBuilder
- func (b OptionBuilder) RetryHook(hook req.RetryHookFunc) OptionBuilder
- func (b OptionBuilder) RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder
- func (b OptionBuilder) TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
- func (b OptionBuilder) TLSFingerprintAndroid() OptionBuilder
- func (b OptionBuilder) TLSFingerprintChrome() OptionBuilder
- func (b OptionBuilder) TLSFingerprintEdge() OptionBuilder
- func (b OptionBuilder) TLSFingerprintFirefox() OptionBuilder
- func (b OptionBuilder) TLSFingerprintIOS() OptionBuilder
- func (b OptionBuilder) TLSFingerprintRandomized() OptionBuilder
- func (b OptionBuilder) TLSFingerprintSafari() OptionBuilder
- func (b OptionBuilder) Timeout(d time.Duration) OptionBuilder
- func (b OptionBuilder) Trace() OptionBuilder
- func (b OptionBuilder) TraceAll() OptionBuilder
- func (b OptionBuilder) Transport(rt http.RoundTripper) OptionBuilder
- func (b OptionBuilder) UploadCallback(callback req.UploadCallback) OptionBuilder
- func (b OptionBuilder) UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder
- func (b OptionBuilder) UploadProgress() OptionBuilder
- func (b OptionBuilder) UserAgent(value string) OptionBuilder
- type TLSFingerprintKind
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Delete ¶
Delete issues a DELETE request using the provided client. It remains available for compatibility; new code can use Client.Delete. @group Requests
Example: typed DELETE
type DeleteResponse struct {
URL string `json:"url"`
}
c := httpclient.New()
res, err := httpclient.Delete[DeleteResponse](c, "https://httpbin.org/delete")
if err != nil {
return
}
httpclient.Dump(res) // dumps DeleteResponse
// #DeleteResponse {
// URL => "https://httpbin.org/delete" #string
// }
func DeleteCtx ¶
DeleteCtx issues a DELETE request using the provided client and context. It remains available for compatibility; new code can use Client.DeleteCtx. @group Requests (Context)
Example: context-aware DELETE
type DeleteResponse struct {
URL string `json:"url"`
}
ctx := context.Background()
c := httpclient.New()
res, err := httpclient.DeleteCtx[DeleteResponse](c, ctx, "https://httpbin.org/delete")
if err != nil {
return
}
httpclient.Dump(res) // dumps DeleteResponse
// #DeleteResponse {
// URL => "https://httpbin.org/delete" #string
// }
func Do ¶
Do executes a pre-configured req request and returns the decoded body and response. This is the low-level escape hatch when you need full req control. @group Requests
Example: advanced request with response access
r := req.C().R().SetHeader("X-Trace", "1")
r.SetURL("https://httpbin.org/headers")
r.Method = http.MethodGet
res, rawResp, err := httpclient.Do[map[string]any](r)
if err != nil {
return
}
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// X-Trace => "1" #string
// }
// }
println(rawResp.StatusCode)
func Dump ¶
func Dump(values ...any)
Dump prints values using the bundled godump formatter. @group Debugging
Example: dump a response
res, _ := httpclient.Get[map[string]any](httpclient.Default(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func Get ¶
Get issues a GET request using the provided client. It remains available for compatibility; new code can use Client.Get. @group Requests
Example: bind to a struct
type GetResponse struct {
URL string `json:"url"`
}
c := httpclient.New()
res, _ := httpclient.Get[GetResponse](c, "https://httpbin.org/get")
httpclient.Dump(res)
// #GetResponse {
// URL => "https://httpbin.org/get" #string
// }
Example: bind to a string body
resString, _ := httpclient.Get[string](c, "https://httpbin.org/uuid")
println(resString) // dumps string
// {
// "uuid": "becbda6d-9950-4966-ae23-0369617ba065"
// }
func GetCtx ¶
GetCtx issues a GET request using the provided client and context. It remains available for compatibility; new code can use Client.GetCtx. @group Requests (Context)
Example: context-aware GET
type GetResponse struct {
URL string `json:"url"`
}
ctx := context.Background()
c := httpclient.New()
res, err := httpclient.GetCtx[GetResponse](c, ctx, "https://httpbin.org/get")
if err != nil {
return
}
httpclient.Dump(res) // dumps GetResponse
// #GetResponse {
// URL => "https://httpbin.org/get" #string
// }
func Head ¶
Head issues a HEAD request using the provided client. It remains available for compatibility; new code can use Client.Head. @group Requests
Example: HEAD request
c := httpclient.New()
_, err := httpclient.Head[string](c, "https://httpbin.org/get")
if err != nil {
return
}
func HeadCtx ¶
HeadCtx issues a HEAD request using the provided client and context. It remains available for compatibility; new code can use Client.HeadCtx. @group Requests (Context)
Example: context-aware HEAD
ctx := context.Background()
c := httpclient.New()
_, err := httpclient.HeadCtx[string](c, ctx, "https://httpbin.org/get")
if err != nil {
return
}
func Options ¶
Options issues an OPTIONS request using the provided client. It remains available for compatibility; new code can use Client.Options. @group Requests
Example: OPTIONS request
c := httpclient.New()
_, err := httpclient.Options[string](c, "https://httpbin.org/get")
if err != nil {
return
}
func OptionsCtx ¶
OptionsCtx issues an OPTIONS request using the provided client and context. It remains available for compatibility; new code can use Client.OptionsCtx. @group Requests (Context)
Example: context-aware OPTIONS
ctx := context.Background()
c := httpclient.New()
_, err := httpclient.OptionsCtx[string](c, ctx, "https://httpbin.org/get")
if err != nil {
return
}
func Patch ¶
Patch issues a PATCH request using the provided client. It remains available for compatibility; new code can use Client.Patch. @group Requests
Example: typed PATCH
type UpdateUser struct {
Name string `json:"name"`
}
type UpdateUserResponse struct {
JSON UpdateUser `json:"json"`
}
c := httpclient.New()
res, err := httpclient.Patch[UpdateUser, UpdateUserResponse](c, "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
if err != nil {
return
}
httpclient.Dump(res) // dumps UpdateUserResponse
// #UpdateUserResponse {
// JSON => #UpdateUser {
// Name => "Ana" #string
// }
// }
func PatchCtx ¶
func PatchCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error)
PatchCtx issues a PATCH request using the provided client and context. It remains available for compatibility; new code can use Client.PatchCtx. @group Requests (Context)
Example: context-aware PATCH
type UpdateUser struct {
Name string `json:"name"`
}
type UpdateUserResponse struct {
JSON UpdateUser `json:"json"`
}
ctx := context.Background()
c := httpclient.New()
res, err := httpclient.PatchCtx[UpdateUser, UpdateUserResponse](c, ctx, "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
if err != nil {
return
}
httpclient.Dump(res) // dumps UpdateUserResponse
// #UpdateUserResponse {
// JSON => #UpdateUser {
// Name => "Ana" #string
// }
// }
func Post ¶
Post issues a POST request using the provided client. It remains available for compatibility; new code can use Client.Post. @group Requests
Example: typed POST
type CreateUser struct {
Name string `json:"name"`
}
type CreateUserResponse struct {
JSON CreateUser `json:"json"`
}
c := httpclient.New()
res, err := httpclient.Post[CreateUser, CreateUserResponse](c, "https://httpbin.org/post", CreateUser{Name: "Ana"})
if err != nil {
return
}
httpclient.Dump(res) // dumps CreateUserResponse
// #CreateUserResponse {
// JSON => #CreateUser {
// Name => "Ana" #string
// }
// }
func PostCtx ¶
func PostCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error)
PostCtx issues a POST request using the provided client and context. It remains available for compatibility; new code can use Client.PostCtx. @group Requests (Context)
Example: context-aware POST
type CreateUser struct {
Name string `json:"name"`
}
type CreateUserResponse struct {
JSON CreateUser `json:"json"`
}
ctx := context.Background()
c := httpclient.New()
res, err := httpclient.PostCtx[CreateUser, CreateUserResponse](c, ctx, "https://httpbin.org/post", CreateUser{Name: "Ana"})
if err != nil {
return
}
httpclient.Dump(res) // dumps CreateUserResponse
// #CreateUserResponse {
// JSON => #CreateUser {
// Name => "Ana" #string
// }
// }
func Put ¶
Put issues a PUT request using the provided client. It remains available for compatibility; new code can use Client.Put. @group Requests
Example: typed PUT
type UpdateUser struct {
Name string `json:"name"`
}
type UpdateUserResponse struct {
JSON UpdateUser `json:"json"`
}
c := httpclient.New()
res, err := httpclient.Put[UpdateUser, UpdateUserResponse](c, "https://httpbin.org/put", UpdateUser{Name: "Ana"})
if err != nil {
return
}
httpclient.Dump(res) // dumps UpdateUserResponse
// #UpdateUserResponse {
// JSON => #UpdateUser {
// Name => "Ana" #string
// }
// }
func PutCtx ¶
func PutCtx[In any, Out any](client *Client, ctx context.Context, url string, body In, opts ...Option) (Out, error)
PutCtx issues a PUT request using the provided client and context. It remains available for compatibility; new code can use Client.PutCtx. @group Requests (Context)
Example: context-aware PUT
type UpdateUser struct {
Name string `json:"name"`
}
type UpdateUserResponse struct {
JSON UpdateUser `json:"json"`
}
ctx := context.Background()
c := httpclient.New()
res, err := httpclient.PutCtx[UpdateUser, UpdateUserResponse](c, ctx, "https://httpbin.org/put", UpdateUser{Name: "Ana"})
if err != nil {
return
}
httpclient.Dump(res) // dumps UpdateUserResponse
// #UpdateUserResponse {
// JSON => #UpdateUser {
// Name => "Ana" #string
// }
// }
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps a req client with typed helpers and defaults. @group Client
func New ¶
New creates a client with opinionated defaults and optional overrides. @group Client
Example: configure all client options
var buf bytes.Buffer
_ = httpclient.New(httpclient.
BaseURL("https://httpbin.org").
Timeout(5*time.Second).
Header("X-Trace", "1").
Header("Accept", "application/json").
Transport(http.RoundTripper(http.DefaultTransport)).
Middleware(func(_ *req.Client, r *req.Request) error {
r.SetHeader("X-Middleware", "1")
return nil
}).
ErrorMapper(func(resp *req.Response) error {
return fmt.Errorf("status %d", resp.StatusCode)
}).
DumpAll().
DumpEachRequest().
DumpEachRequestTo(&buf).
Retry(func(rc *req.Client) {
rc.SetCommonRetryCount(2)
}).
RetryCount(2).
RetryFixedInterval(200*time.Millisecond).
RetryBackoff(100*time.Millisecond, 2*time.Second).
RetryInterval(func(_ *req.Response, attempt int) time.Duration {
return time.Duration(attempt) * 100 * time.Millisecond
}).
RetryCondition(func(resp *req.Response, _ error) bool {
return resp != nil && resp.StatusCode == 503
}).
RetryHook(func(_ *req.Response, _ error) {}),
)
func (*Client) Delete ¶
Delete issues a DELETE request and decodes its response. @group Requests
Example: typed DELETE
type DeleteResponse struct { URL string `json:"url"` }
c := httpclient.New()
res, err := c.Delete[DeleteResponse]("https://httpbin.org/delete")
if err != nil {
return
}
fmt.Println(res.URL)
// https://httpbin.org/delete
func (*Client) DeleteCtx ¶
DeleteCtx issues a context-aware DELETE request and decodes its response. @group Requests (Context)
Example: client context-aware DELETE
type DeleteResponse struct {
URL string `json:"url"`
}
ctx := context.Background()
c := httpclient.New()
res, err := c.DeleteCtx[DeleteResponse](ctx, "https://httpbin.org/delete")
if err != nil {
return
}
fmt.Println(res.URL)
// https://httpbin.org/delete
func (*Client) Get ¶
Get issues a GET request and decodes its response. @group Requests
Example: bind to a struct
type GetResponse struct {
URL string `json:"url"`
}
c := httpclient.New()
res, err := c.Get[GetResponse]("https://httpbin.org/get")
fmt.Println(err == nil, res.URL)
// true https://httpbin.org/get
func (*Client) GetCtx ¶
GetCtx issues a context-aware GET request and decodes its response. @group Requests (Context)
Example: client context-aware GET
type GetResponse struct {
URL string `json:"url"`
}
ctx := context.Background()
c := httpclient.New()
res, err := c.GetCtx[GetResponse](ctx, "https://httpbin.org/get")
fmt.Println(err == nil, res.URL)
// true https://httpbin.org/get
func (*Client) Head ¶
Head issues a HEAD request and decodes its response using the established response contract. @group Requests
Example: client HEAD request
c := httpclient.New()
_, err := c.Head[[]byte]("https://httpbin.org/get")
fmt.Println(err == nil)
// true
func (*Client) HeadCtx ¶
HeadCtx issues a context-aware HEAD request and decodes its response using the established response contract. @group Requests (Context)
Example: client context-aware HEAD
ctx := context.Background() c := httpclient.New() _, err := c.HeadCtx[[]byte](ctx, "https://httpbin.org/get") fmt.Println(err == nil) // true
func (*Client) Options ¶
Options issues an OPTIONS request and decodes its response. @group Requests
Example: client OPTIONS request
c := httpclient.New()
_, err := c.Options[[]byte]("https://httpbin.org/get")
fmt.Println(err == nil)
// true
func (*Client) OptionsCtx ¶
OptionsCtx issues a context-aware OPTIONS request and decodes its response. @group Requests (Context)
Example: client context-aware OPTIONS
ctx := context.Background() c := httpclient.New() _, err := c.OptionsCtx[[]byte](ctx, "https://httpbin.org/get") fmt.Println(err == nil) // true
func (*Client) Patch ¶
Patch issues a PATCH request and decodes its response. @group Requests
Example: typed PATCH
type UpdateUser struct { Name string `json:"name"` }
type UpdateUserResponse struct { JSON UpdateUser `json:"json"` }
c := httpclient.New()
res, err := c.Patch[UpdateUserResponse]("https://httpbin.org/patch", UpdateUser{Name: "Ana"})
if err != nil {
return
}
fmt.Println(res.JSON.Name)
// Ana
func (*Client) PatchCtx ¶
func (c *Client) PatchCtx[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)
PatchCtx issues a context-aware PATCH request and decodes its response. @group Requests (Context)
Example: client context-aware PATCH
type UpdateUser struct { Name string `json:"name"` }
type UpdateUserResponse struct { JSON UpdateUser `json:"json"` }
ctx := context.Background()
c := httpclient.New()
res, err := c.PatchCtx[UpdateUserResponse](ctx, "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
if err != nil {
return
}
fmt.Println(res.JSON.Name)
// Ana
func (*Client) Post ¶
Post issues a POST request and decodes its response. @group Requests
Example: typed POST
type CreateUser struct { Name string `json:"name"` }
type CreateUserResponse struct { JSON CreateUser `json:"json"` }
c := httpclient.New()
res, err := c.Post[CreateUserResponse]("https://httpbin.org/post", CreateUser{Name: "Ana"})
if err != nil {
return
}
fmt.Println(res.JSON.Name)
// Ana
func (*Client) PostCtx ¶
func (c *Client) PostCtx[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)
PostCtx issues a context-aware POST request and decodes its response. @group Requests (Context)
Example: client context-aware POST
type CreateUser struct { Name string `json:"name"` }
type CreateUserResponse struct { JSON CreateUser `json:"json"` }
ctx := context.Background()
c := httpclient.New()
res, err := c.PostCtx[CreateUserResponse](ctx, "https://httpbin.org/post", CreateUser{Name: "Ana"})
if err != nil {
return
}
fmt.Println(res.JSON.Name)
// Ana
func (*Client) Put ¶
Put issues a PUT request and decodes its response. @group Requests
Example: typed PUT
type UpdateUser struct { Name string `json:"name"` }
type UpdateUserResponse struct { JSON UpdateUser `json:"json"` }
c := httpclient.New()
res, err := c.Put[UpdateUserResponse]("https://httpbin.org/put", UpdateUser{Name: "Ana"})
if err != nil {
return
}
fmt.Println(res.JSON.Name)
// Ana
func (*Client) PutCtx ¶
func (c *Client) PutCtx[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)
PutCtx issues a context-aware PUT request and decodes its response. @group Requests (Context)
Example: client context-aware PUT
type UpdateUser struct { Name string `json:"name"` }
type UpdateUserResponse struct { JSON UpdateUser `json:"json"` }
ctx := context.Background()
c := httpclient.New()
res, err := c.PutCtx[UpdateUserResponse](ctx, "https://httpbin.org/put", UpdateUser{Name: "Ana"})
if err != nil {
return
}
fmt.Println(res.JSON.Name)
// Ana
type ErrorMapperFunc ¶
ErrorMapperFunc customizes error creation for non-2xx responses.
type HTTPError ¶
func (*HTTPError) Error ¶
Error returns a short, human-friendly summary of the HTTP error. @group Errors
Example: check for HTTP errors
type User struct {
Name string `json:"name"`
}
c := httpclient.New()
res, err := httpclient.Get[map[string]any](c, "https://httpbin.org/status/404")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
var httpErr *httpclient.HTTPError
if errors.As(err, &httpErr) {
_ = httpErr.StatusCode
}
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option applies configuration to a client or request.
type OptionBuilder ¶
type OptionBuilder struct {
// contains filtered or unexported fields
}
OptionBuilder chains request and client options. @group Options
Example: chain options
opt := httpclient.Header("X-Trace", "1").Query("q", "go")
_ = opt
func AsChrome ¶
func AsChrome() OptionBuilder
AsChrome applies the Chrome browser profile (headers including User-Agent, TLS, and HTTP/2 behavior). @group Browser Profiles
Applies to client configuration only. Example: use a Chrome profile
_ = httpclient.New(httpclient.AsChrome())
func AsFirefox ¶
func AsFirefox() OptionBuilder
AsFirefox applies the Firefox browser profile (headers including User-Agent, TLS, and HTTP/2 behavior). @group Browser Profiles
Applies to client configuration only. Example: use a Firefox profile
c := httpclient.New(httpclient.AsFirefox())
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// User-Agent => "<user-agent>" #string
// }
// }
func AsMobile ¶
func AsMobile() OptionBuilder
AsMobile applies a mobile Chrome-like profile (headers including User-Agent, TLS, and HTTP/2 behavior). @group Browser Profiles
Applies to client configuration only. Example: use a mobile profile
_ = httpclient.New(httpclient.AsMobile())
func AsSafari ¶
func AsSafari() OptionBuilder
AsSafari applies the Safari browser profile (headers including User-Agent, TLS, and HTTP/2 behavior). @group Browser Profiles
Applies to client configuration only. Example: use a Safari profile
_ = httpclient.New(httpclient.AsSafari())
func Auth ¶
func Auth(scheme, token string) OptionBuilder
Auth sets the Authorization header using a scheme and token. @group Auth Applies to both client defaults and request-time overrides.
Example: custom auth scheme
// Apply to all requests
c := httpclient.New(httpclient.Auth("Token", "abc123"))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Authorization => "Token abc123" #string
// }
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/headers", httpclient.Auth("Token", "abc123"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Authorization => "Token abc123" #string
// }
// }
func BaseURL ¶
func BaseURL(url string) OptionBuilder
BaseURL sets a base URL on the client. @group Client Options
Applies to client configuration only. Example: client base URL
c := httpclient.New(httpclient.BaseURL("https://httpbin.org"))
res, _ := httpclient.Get[map[string]any](c, "/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func Basic ¶
func Basic(user, pass string) OptionBuilder
Basic sets HTTP basic authentication headers. @group Auth Applies to both client defaults and request-time overrides.
Example: basic auth
// Apply to all requests
c := httpclient.New(httpclient.Basic("user", "pass"))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Authorization => "Basic dXNlcjpwYXNz" #string
// }
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/headers", httpclient.Basic("user", "pass"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Authorization => "Basic dXNlcjpwYXNz" #string
// }
// }
func Bearer ¶
func Bearer(token string) OptionBuilder
Bearer sets the Authorization header with a bearer token. @group Auth Applies to both client defaults and request-time overrides.
Example: bearer auth
// Apply to all requests
c := httpclient.New(httpclient.Bearer("token"))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Authorization => "Bearer token" #string
// }
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/headers", httpclient.Bearer("token"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Authorization => "Bearer token" #string
// }
// }
func Before ¶
func Before(fn func(*req.Request)) OptionBuilder
Before runs a hook before the request is sent. @group Request Control
Applies to individual requests only. Example: mutate req.Request
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/get", httpclient.Before(func(r *req.Request) {
r.EnableDump()
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// url => "https://httpbin.org/get" #string
// }
func Body ¶
func Body(value any) OptionBuilder
Body sets the request body and infers JSON for structs and maps. @group Request Composition
Applies to individual requests only. Example: send JSON body with inference
type Payload struct {
Name string `json:"name"`
}
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.Body(Payload{Name: "Ana"}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// json => #map[string]interface {} {
// name => "Ana" #string
// }
// }
func CookieJar ¶
func CookieJar(jar http.CookieJar) OptionBuilder
CookieJar sets the cookie jar for the client. @group Client Options
Applies to client configuration only. Example: set cookie jar and seed cookies
jar, _ := cookiejar.New(nil)
u, _ := url.Parse("https://httpbin.org")
jar.SetCookies(u, []*http.Cookie{
{Name: "session", Value: "abc123"},
})
c := httpclient.New(httpclient.CookieJar(jar))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/cookies")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// cookies => #map[string]interface {} {
// session => "abc123" #string
// }
// }
func DumpAll ¶
func DumpAll() OptionBuilder
DumpAll enables req's client-level dump output for all requests. @group Debugging
Applies to the client configuration only. Example: dump every request and response
c := httpclient.New(httpclient.DumpAll())
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func DumpEachRequest ¶
func DumpEachRequest() OptionBuilder
DumpEachRequest enables request-level dumps for each request on the client. @group Debugging
Applies to the client configuration only. Example: dump each request as it is sent
c := httpclient.New(httpclient.DumpEachRequest())
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func DumpEachRequestTo ¶
func DumpEachRequestTo(output io.Writer) OptionBuilder
DumpEachRequestTo enables request-level dumps for each request and writes them to the provided output. @group Debugging
Applies to the client configuration only. Example: dump each request to a buffer
var buf bytes.Buffer
c := httpclient.New(httpclient.DumpEachRequestTo(&buf))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
_ = buf.String()
func DumpTo ¶
func DumpTo(output io.Writer) OptionBuilder
DumpTo enables req's request-level dump output to a writer. @group Debugging
Applies to individual requests only. Example: dump to a buffer
var buf bytes.Buffer
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.DumpTo(&buf))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func DumpToFile ¶
func DumpToFile(filename string) OptionBuilder
DumpToFile enables req's request-level dump output to a file path. @group Debugging
Applies to individual requests only. Example: dump to a file
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.DumpToFile("httpclient.dump"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func EnableDump ¶
func EnableDump() OptionBuilder
EnableDump enables req's request-level dump output. @group Debugging
Applies to individual requests only. Example: dump a single request
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.EnableDump())
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func ErrorMapper ¶
func ErrorMapper(fn ErrorMapperFunc) OptionBuilder
ErrorMapper sets a custom error mapper for non-2xx responses. @group Client Options
Applies only to the client configuration. Example: map error responses
c := httpclient.New(httpclient.ErrorMapper(func(resp *req.Response) error {
return fmt.Errorf("status %d", resp.StatusCode)
}))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/status/500")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
func File ¶
func File(paramName, filePath string) OptionBuilder
File attaches a file from disk as multipart form data. @group Upload Options
Applies to individual requests only. Example: upload a file
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.File("file", "/tmp/report.txt"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// file => "hello" #string
// }
// }
func FileBytes ¶
func FileBytes(paramName, filename string, content []byte) OptionBuilder
FileBytes attaches a file from bytes as multipart form data. @group Upload Options
Applies to individual requests only. Example: upload bytes as a file
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.FileBytes("file", "report.txt", []byte("hello")))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// file => "hello" #string
// }
// }
func FileReader ¶
func FileReader(paramName, filename string, reader io.Reader) OptionBuilder
FileReader attaches a file from a reader as multipart form data. @group Upload Options
Applies to individual requests only. Example: upload from reader
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.FileReader("file", "report.txt", strings.NewReader("hello")))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// file => "hello" #string
// }
// }
func Files ¶
func Files(files map[string]string) OptionBuilder
Files attaches multiple files from disk as multipart form data. @group Upload Options
Applies to individual requests only. Example: upload multiple files
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.Files(map[string]string{
"fileA": "/tmp/a.txt",
"fileB": "/tmp/b.txt",
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// fileA => "hello" #string
// fileB => "world" #string
// }
// }
func Form ¶
func Form(values map[string]string) OptionBuilder
Form sets form data for the request. @group Request Composition
Applies to individual requests only. Example: submit a form
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.Form(map[string]string{
"name": "alice",
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// form => #map[string]interface {} {
// name => "alice" #string
// }
// }
func Header ¶
func Header(key, value string) OptionBuilder
Header sets a header on a request or client. @group Request Composition
Applies to both client defaults and request-time headers. Example: apply a header
// Apply to all requests
c := httpclient.New(httpclient.Header("X-Trace", "1"))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// X-Trace => "1" #string
// }
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/headers", httpclient.Header("X-Trace", "1"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// X-Trace => "1" #string
// }
// }
func Headers ¶
func Headers(values map[string]string) OptionBuilder
Headers sets multiple headers on a request or client. @group Request Composition
Applies to both client defaults and request-time headers. Example: apply headers
// Apply to all requests
c := httpclient.New(httpclient.Headers(map[string]string{
"X-Trace": "1",
"Accept": "application/json",
}))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Accept => "application/json" #string
// X-Trace => "1" #string
// }
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/headers", httpclient.Headers(map[string]string{
"X-Trace": "1",
"Accept": "application/json",
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// Accept => "application/json" #string
// X-Trace => "1" #string
// }
// }
func JSON ¶
func JSON(value any) OptionBuilder
JSON forces JSON encoding for the request body (even when inference might choose differently). @group Request Composition
Applies to individual requests only. Example: force JSON body
type Payload struct {
Name string `json:"name"`
}
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil, httpclient.JSON(Payload{Name: "Ana"}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// json => #map[string]interface {} {
// name => "Ana" #string
// }
// }
func Middleware ¶
func Middleware(mw ...req.RequestMiddleware) OptionBuilder
Middleware adds request middleware to the client. @group Client Options
Applies only to the client configuration. Example: add request middleware
c := httpclient.New(httpclient.Middleware(func(_ *req.Client, r *req.Request) error {
r.SetHeader("X-Trace", "1")
return nil
}))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// X-Trace => "1" #string
// }
// }
func OutputFile ¶
func OutputFile(path string) OptionBuilder
OutputFile streams the response body to a file path. @group Download Options
Applies to individual requests only. Example: download to file
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/bytes/1024", httpclient.OutputFile("/tmp/file.bin"))
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
func Path ¶
func Path(key string, value any) OptionBuilder
Path sets a path parameter by name. @group Request Composition
Applies to individual requests only. Example: path parameter
type User struct {
Name string `json:"name"`
}
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/anything/{id}", httpclient.Path("id", 42))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// url => "https://httpbin.org/anything/42" #string
// }
func Paths ¶
func Paths(values map[string]any) OptionBuilder
Paths sets multiple path parameters from a map. @group Request Composition
Applies to individual requests only. Example: path parameters
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/anything/{org}/users/{id}", httpclient.Paths(map[string]any{
"org": "goforj",
"id": 7,
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// url => "https://httpbin.org/anything/goforj/users/7" #string
// }
func Proxy ¶
func Proxy(proxyURL string) OptionBuilder
Proxy sets a proxy URL for the client. @group Client Options
Applies to client configuration only. Example: set proxy URL
c := httpclient.New(httpclient.Proxy("http://localhost:8080"))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/get")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
func ProxyFunc ¶
ProxyFunc sets a proxy function for the client. @group Client Options
Applies to client configuration only. Example: set proxy function
c := httpclient.New(httpclient.ProxyFunc(http.ProxyFromEnvironment))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func Queries ¶
func Queries(values map[string]string) OptionBuilder
Queries sets query parameters from a map. @group Request Composition
Applies to individual requests only. Example: add query params
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/get", httpclient.Queries(map[string]string{
"q": "search",
"ok": "1",
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// args => #map[string]interface {} {
// ok => "1" #string
// q => "search" #string
// }
// }
func Query ¶
func Query(kv ...string) OptionBuilder
Query adds query parameters as key/value pairs. @group Request Composition
Applies to individual requests only. Example: add query params
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/get", httpclient.Query("q", "search"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// args => #map[string]interface {} {
// q => "search" #string
// }
// }
func Redirect ¶
func Redirect(policies ...req.RedirectPolicy) OptionBuilder
Redirect sets the redirect policy for the client. @group Client Options
Applies to client configuration only. Example: disable redirects
c := httpclient.New(httpclient.Redirect(req.NoRedirectPolicy()))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/redirect/1")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
func Retry ¶
func Retry(fn func(*req.Client)) OptionBuilder
Retry applies a custom retry configuration to the client. Defaults remain in effect unless the callback modifies them. @group Retry (Client)
Applies only to client configuration. Example: configure client retry
_ = httpclient.New(httpclient.Retry(func(rc *req.Client) {
rc.SetCommonRetryCount(2)
}))
func RetryBackoff ¶
func RetryBackoff(min, max time.Duration) OptionBuilder
RetryBackoff sets a capped exponential backoff retry interval for a request. Overrides the req default interval (fixed 100ms) with jittered backoff. @group Retry
Applies to both client defaults and individual requests. Example: retry backoff
// Apply to all requests
c := httpclient.New(httpclient.RetryBackoff(100*time.Millisecond, 2*time.Second))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.RetryBackoff(100*time.Millisecond, 2*time.Second))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func RetryCondition ¶
func RetryCondition(condition req.RetryConditionFunc) OptionBuilder
RetryCondition sets the retry condition for a request. Overrides the default behavior (retry only when a request error occurs). @group Retry
Applies to both client defaults and individual requests. Example: retry on 503
// Apply to all requests
c := httpclient.New(httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
return resp != nil && resp.StatusCode == 503
}))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/status/503")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/status/503", httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
return resp != nil && resp.StatusCode == 503
}))
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
func RetryCount ¶
func RetryCount(count int) OptionBuilder
RetryCount enables retry for a request and sets the maximum retry count. Default behavior from req: retries are disabled (count = 0). When enabled, retries happen only on request errors unless RetryCondition is set, and the default interval is a fixed 100ms between attempts. @group Retry
Applies to both client defaults and individual requests. Example: retry count
// Apply to all requests
c := httpclient.New(httpclient.RetryCount(2))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.RetryCount(2))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func RetryFixedInterval ¶
func RetryFixedInterval(interval time.Duration) OptionBuilder
RetryFixedInterval sets a fixed retry interval for a request. Overrides the req default interval (fixed 100ms). @group Retry
Applies to both client defaults and individual requests. Example: retry interval
// Apply to all requests
c := httpclient.New(httpclient.RetryFixedInterval(200 * time.Millisecond))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.RetryFixedInterval(200*time.Millisecond))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func RetryHook ¶
func RetryHook(hook req.RetryHookFunc) OptionBuilder
RetryHook registers a retry hook for a request. Runs before each retry attempt; no hooks are configured by default. @group Retry
Applies to both client defaults and individual requests. Example: hook on retry
// Apply to all requests
c := httpclient.New(httpclient.RetryHook(func(_ *req.Response, _ error) {}))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.RetryHook(func(_ *req.Response, _ error) {}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func RetryInterval ¶
func RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder
RetryInterval sets a custom retry interval function for a request. Overrides the req default interval (fixed 100ms). @group Retry
Applies to both client defaults and individual requests. Example: custom retry interval
// Apply to all requests
c := httpclient.New(httpclient.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
return time.Duration(attempt) * 100 * time.Millisecond
}))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
return time.Duration(attempt) * 100 * time.Millisecond
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func TLSFingerprint ¶
func TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
TLSFingerprint applies a TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply a TLS fingerprint preset
_ = httpclient.New(httpclient.TLSFingerprint(httpclient.TLSFingerprintChromeKind))
func TLSFingerprintAndroid ¶
func TLSFingerprintAndroid() OptionBuilder
TLSFingerprintAndroid applies the Android TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply Android TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintAndroid())
func TLSFingerprintChrome ¶
func TLSFingerprintChrome() OptionBuilder
TLSFingerprintChrome applies the Chrome TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply Chrome TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintChrome())
func TLSFingerprintEdge ¶
func TLSFingerprintEdge() OptionBuilder
TLSFingerprintEdge applies the Edge TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply Edge TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintEdge())
func TLSFingerprintFirefox ¶
func TLSFingerprintFirefox() OptionBuilder
TLSFingerprintFirefox applies the Firefox TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply Firefox TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintFirefox())
func TLSFingerprintIOS ¶
func TLSFingerprintIOS() OptionBuilder
TLSFingerprintIOS applies the iOS TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply iOS TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintIOS())
func TLSFingerprintRandomized ¶
func TLSFingerprintRandomized() OptionBuilder
TLSFingerprintRandomized applies a randomized TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply randomized TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintRandomized())
func TLSFingerprintSafari ¶
func TLSFingerprintSafari() OptionBuilder
TLSFingerprintSafari applies the Safari TLS fingerprint preset. @group Advanced
Applies to client configuration only. Example: apply Safari TLS fingerprint
_ = httpclient.New(httpclient.TLSFingerprintSafari())
func Timeout ¶
func Timeout(d time.Duration) OptionBuilder
Timeout sets a per-request timeout using context cancellation. @group Request Control
Applies to both client defaults (via WithTimeout) and individual requests. Example: timeout
// Apply to all requests
c := httpclient.New(httpclient.Timeout(2 * time.Second))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/delay/2")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/delay/2", httpclient.Timeout(2*time.Second))
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
func Trace ¶
func Trace() OptionBuilder
Trace enables req's request-level trace output. @group Debugging
Applies to individual requests only. Example: trace a single request
c := httpclient.New()
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid", httpclient.Trace())
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func TraceAll ¶
func TraceAll() OptionBuilder
TraceAll enables req's client-level trace output for all requests. @group Debugging
Applies to the client configuration only. Example: trace all requests
c := httpclient.New(httpclient.TraceAll())
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func Transport ¶
func Transport(rt http.RoundTripper) OptionBuilder
Transport wraps the underlying transport with a custom RoundTripper. @group Client Options
Applies to client configuration only. Example: wrap transport
c := httpclient.New(httpclient.Transport(http.RoundTripper(http.DefaultTransport)))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// uuid => "<uuid>" #string
// }
func UploadCallback ¶
func UploadCallback(callback req.UploadCallback) OptionBuilder
UploadCallback registers a callback for upload progress. @group Upload Options
Applies to individual requests only. Example: track upload progress
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil,
httpclient.File("file", "/tmp/report.bin"),
httpclient.UploadCallback(func(info req.UploadInfo) {
percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
fmt.Printf("\rprogress: %.1f%%", percent)
if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
fmt.Print("\n")
}
}),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// file => "<file>" #string
// }
// }
func UploadCallbackWithInterval ¶
func UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder
UploadCallbackWithInterval registers a callback for upload progress with a minimum interval. @group Upload Options
Applies to individual requests only. Example: throttle upload progress updates
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil,
httpclient.File("file", "/tmp/report.bin"),
httpclient.UploadCallbackWithInterval(func(info req.UploadInfo) {
percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
fmt.Printf("\rprogress: %.1f%% (%.0f bytes)", percent, float64(info.UploadedSize))
if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
fmt.Print("\n")
}
}, 200*time.Millisecond),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// file => "<file>" #string
// }
// }
func UploadProgress ¶
func UploadProgress() OptionBuilder
UploadProgress enables a default progress spinner and bar for uploads. @group Upload Options Applies to individual requests only.
Example: upload with automatic progress
c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](c, "https://httpbin.org/post", nil,
httpclient.File("file", "/tmp/report.bin"),
httpclient.UploadProgress(),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// files => #map[string]interface {} {
// file => "<file>" #string
// }
// }
func UserAgent ¶
func UserAgent(value string) OptionBuilder
UserAgent sets the User-Agent header on a request or client. @group Request Composition
Applies to both client defaults and request-time headers. Example: set a User-Agent
// Apply to all requests
c := httpclient.New(httpclient.UserAgent("my-app/1.0"))
res, _ := httpclient.Get[map[string]any](c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// User-Agent => "my-app/1.0" #string
// }
// }
// Apply to a single request
res, _ = httpclient.Get[map[string]any](c, "https://httpbin.org/headers", httpclient.UserAgent("my-app/1.0"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
// headers => #map[string]interface {} {
// User-Agent => "my-app/1.0" #string
// }
// }
func (OptionBuilder) AsChrome ¶
func (b OptionBuilder) AsChrome() OptionBuilder
func (OptionBuilder) AsFirefox ¶
func (b OptionBuilder) AsFirefox() OptionBuilder
func (OptionBuilder) AsMobile ¶
func (b OptionBuilder) AsMobile() OptionBuilder
func (OptionBuilder) AsSafari ¶
func (b OptionBuilder) AsSafari() OptionBuilder
func (OptionBuilder) Auth ¶
func (b OptionBuilder) Auth(scheme, token string) OptionBuilder
func (OptionBuilder) BaseURL ¶
func (b OptionBuilder) BaseURL(url string) OptionBuilder
func (OptionBuilder) Basic ¶
func (b OptionBuilder) Basic(user, pass string) OptionBuilder
func (OptionBuilder) Bearer ¶
func (b OptionBuilder) Bearer(token string) OptionBuilder
func (OptionBuilder) Before ¶
func (b OptionBuilder) Before(fn func(*req.Request)) OptionBuilder
func (OptionBuilder) Body ¶
func (b OptionBuilder) Body(value any) OptionBuilder
func (OptionBuilder) CookieJar ¶
func (b OptionBuilder) CookieJar(jar http.CookieJar) OptionBuilder
func (OptionBuilder) DumpAll ¶
func (b OptionBuilder) DumpAll() OptionBuilder
func (OptionBuilder) DumpEachRequest ¶
func (b OptionBuilder) DumpEachRequest() OptionBuilder
func (OptionBuilder) DumpEachRequestTo ¶
func (b OptionBuilder) DumpEachRequestTo(output io.Writer) OptionBuilder
func (OptionBuilder) DumpTo ¶
func (b OptionBuilder) DumpTo(output io.Writer) OptionBuilder
func (OptionBuilder) DumpToFile ¶
func (b OptionBuilder) DumpToFile(filename string) OptionBuilder
DumpToFile configures file output for one request and releases the file after each write.
func (OptionBuilder) EnableDump ¶
func (b OptionBuilder) EnableDump() OptionBuilder
func (OptionBuilder) ErrorMapper ¶
func (b OptionBuilder) ErrorMapper(fn ErrorMapperFunc) OptionBuilder
func (OptionBuilder) File ¶
func (b OptionBuilder) File(paramName, filePath string) OptionBuilder
func (OptionBuilder) FileBytes ¶
func (b OptionBuilder) FileBytes(paramName, filename string, content []byte) OptionBuilder
func (OptionBuilder) FileReader ¶
func (b OptionBuilder) FileReader(paramName, filename string, reader io.Reader) OptionBuilder
func (OptionBuilder) Files ¶
func (b OptionBuilder) Files(files map[string]string) OptionBuilder
func (OptionBuilder) Form ¶
func (b OptionBuilder) Form(values map[string]string) OptionBuilder
func (OptionBuilder) Header ¶
func (b OptionBuilder) Header(key, value string) OptionBuilder
func (OptionBuilder) Headers ¶
func (b OptionBuilder) Headers(values map[string]string) OptionBuilder
func (OptionBuilder) JSON ¶
func (b OptionBuilder) JSON(value any) OptionBuilder
func (OptionBuilder) Middleware ¶
func (b OptionBuilder) Middleware(mw ...req.RequestMiddleware) OptionBuilder
func (OptionBuilder) OutputFile ¶
func (b OptionBuilder) OutputFile(path string) OptionBuilder
func (OptionBuilder) Path ¶
func (b OptionBuilder) Path(key string, value any) OptionBuilder
func (OptionBuilder) Paths ¶
func (b OptionBuilder) Paths(values map[string]any) OptionBuilder
func (OptionBuilder) Proxy ¶
func (b OptionBuilder) Proxy(proxyURL string) OptionBuilder
func (OptionBuilder) ProxyFunc ¶
func (b OptionBuilder) ProxyFunc(fn func(*http.Request) (*url.URL, error)) OptionBuilder
func (OptionBuilder) Queries ¶
func (b OptionBuilder) Queries(values map[string]string) OptionBuilder
func (OptionBuilder) Query ¶
func (b OptionBuilder) Query(kv ...string) OptionBuilder
func (OptionBuilder) Redirect ¶
func (b OptionBuilder) Redirect(policies ...req.RedirectPolicy) OptionBuilder
func (OptionBuilder) Retry ¶
func (b OptionBuilder) Retry(fn func(*req.Client)) OptionBuilder
func (OptionBuilder) RetryBackoff ¶
func (b OptionBuilder) RetryBackoff(min, max time.Duration) OptionBuilder
func (OptionBuilder) RetryCondition ¶
func (b OptionBuilder) RetryCondition(condition req.RetryConditionFunc) OptionBuilder
func (OptionBuilder) RetryCount ¶
func (b OptionBuilder) RetryCount(count int) OptionBuilder
func (OptionBuilder) RetryFixedInterval ¶
func (b OptionBuilder) RetryFixedInterval(interval time.Duration) OptionBuilder
func (OptionBuilder) RetryHook ¶
func (b OptionBuilder) RetryHook(hook req.RetryHookFunc) OptionBuilder
func (OptionBuilder) RetryInterval ¶
func (b OptionBuilder) RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder
func (OptionBuilder) TLSFingerprint ¶
func (b OptionBuilder) TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
func (OptionBuilder) TLSFingerprintAndroid ¶
func (b OptionBuilder) TLSFingerprintAndroid() OptionBuilder
func (OptionBuilder) TLSFingerprintChrome ¶
func (b OptionBuilder) TLSFingerprintChrome() OptionBuilder
func (OptionBuilder) TLSFingerprintEdge ¶
func (b OptionBuilder) TLSFingerprintEdge() OptionBuilder
func (OptionBuilder) TLSFingerprintFirefox ¶
func (b OptionBuilder) TLSFingerprintFirefox() OptionBuilder
func (OptionBuilder) TLSFingerprintIOS ¶
func (b OptionBuilder) TLSFingerprintIOS() OptionBuilder
func (OptionBuilder) TLSFingerprintRandomized ¶
func (b OptionBuilder) TLSFingerprintRandomized() OptionBuilder
func (OptionBuilder) TLSFingerprintSafari ¶
func (b OptionBuilder) TLSFingerprintSafari() OptionBuilder
func (OptionBuilder) Timeout ¶
func (b OptionBuilder) Timeout(d time.Duration) OptionBuilder
func (OptionBuilder) Trace ¶
func (b OptionBuilder) Trace() OptionBuilder
func (OptionBuilder) TraceAll ¶
func (b OptionBuilder) TraceAll() OptionBuilder
func (OptionBuilder) Transport ¶
func (b OptionBuilder) Transport(rt http.RoundTripper) OptionBuilder
func (OptionBuilder) UploadCallback ¶
func (b OptionBuilder) UploadCallback(callback req.UploadCallback) OptionBuilder
func (OptionBuilder) UploadCallbackWithInterval ¶
func (b OptionBuilder) UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder
func (OptionBuilder) UploadProgress ¶
func (b OptionBuilder) UploadProgress() OptionBuilder
func (OptionBuilder) UserAgent ¶
func (b OptionBuilder) UserAgent(value string) OptionBuilder
type TLSFingerprintKind ¶
type TLSFingerprintKind int
TLSFingerprintKind selects a TLS fingerprint preset.
const ( TLSFingerprintChromeKind TLSFingerprintKind = iota TLSFingerprintFirefoxKind TLSFingerprintSafariKind TLSFingerprintEdgeKind TLSFingerprintAndroidKind TLSFingerprintIOSKind TLSFingerprintRandomizedKind )