package httpx
Import Path
github.com/goforj/httpx (on go.dev)
Dependency Relation
imports 19 packages, and imported by one package
Involved Source Files
client.go
decode.go
errors.go
options_auth.go
options_client.go
options_debug.go
options_download.go
options_impersonate.go
options_profile.go
options_request.go
options_retry.go
options_upload.go
types.go
Package-Level Type Names (total 7)
Client wraps a req client with typed helpers and defaults.
@group Client
Example: create a client
c := httpx.New()
_ = c
Raw returns the underlying req client for chaining raw requests.
@group Client
Example: drop down to req
c := httpx.New()
resp, err := c.Raw().R().Get("https://httpbin.org/uuid")
_, _ = resp, err
Req returns the underlying req client for advanced usage.
@group Client
Example: enable req debugging
c := httpx.New()
c.Req().EnableDumpEachRequest()
func Default() *Client
func New(opts ...Option) *Client
func Delete[T](client *Client, url string, opts ...Option) Result[T]
func DeleteCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Get[T](client *Client, url string, opts ...Option) Result[T]
func GetCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Head[T](client *Client, url string, opts ...Option) Result[T]
func HeadCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Options[T](client *Client, url string, opts ...Option) Result[T]
func OptionsCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Patch[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PatchCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
func Post[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PostCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
func Put[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PutCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
ErrorMapperFunc customizes error creation for non-2xx responses.
func ErrorMapper(fn ErrorMapperFunc) OptionBuilder
func OptionBuilder.ErrorMapper(fn ErrorMapperFunc) OptionBuilder
Body []byte
Header http.Header
Status string
StatusCode int
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 := httpx.New()
res := httpx.Get[User](c, "https://example.com/users/1")
var httpErr *httpx.HTTPError
if errors.As(res.Err, &httpErr) {
_ = httpErr.StatusCode
}
*HTTPError : error
Option applies configuration to a client or request.
OptionBuilder
func Delete[T](client *Client, url string, opts ...Option) Result[T]
func DeleteCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Get[T](client *Client, url string, opts ...Option) Result[T]
func GetCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Head[T](client *Client, url string, opts ...Option) Result[T]
func HeadCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func New(opts ...Option) *Client
func Options[T](client *Client, url string, opts ...Option) Result[T]
func OptionsCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Patch[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PatchCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
func Post[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PostCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
func Put[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PutCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
OptionBuilder chains request and client options.
@group Options
Example: chain options
opt := httpx.Header("X-Trace", "1").Query("q", "go")
_ = opt
( OptionBuilder) AsChrome() OptionBuilder
( OptionBuilder) AsFirefox() OptionBuilder
( OptionBuilder) AsMobile() OptionBuilder
( OptionBuilder) AsSafari() OptionBuilder
( OptionBuilder) Auth(scheme, token string) OptionBuilder
( OptionBuilder) BaseURL(url string) OptionBuilder
( OptionBuilder) Basic(user, pass string) OptionBuilder
( OptionBuilder) Bearer(token string) OptionBuilder
( OptionBuilder) Before(fn func(*req.Request)) OptionBuilder
( OptionBuilder) Body(value any) OptionBuilder
( OptionBuilder) CookieJar(jar http.CookieJar) OptionBuilder
( OptionBuilder) Dump() OptionBuilder
( OptionBuilder) DumpAll() OptionBuilder
( OptionBuilder) DumpEachRequest() OptionBuilder
( OptionBuilder) DumpEachRequestTo(output io.Writer) OptionBuilder
( OptionBuilder) DumpTo(output io.Writer) OptionBuilder
( OptionBuilder) DumpToFile(filename string) OptionBuilder
( OptionBuilder) ErrorMapper(fn ErrorMapperFunc) OptionBuilder
( OptionBuilder) File(paramName, filePath string) OptionBuilder
( OptionBuilder) FileBytes(paramName, filename string, content []byte) OptionBuilder
( OptionBuilder) FileReader(paramName, filename string, reader io.Reader) OptionBuilder
( OptionBuilder) Files(files map[string]string) OptionBuilder
( OptionBuilder) Form(values map[string]string) OptionBuilder
( OptionBuilder) Header(key, value string) OptionBuilder
( OptionBuilder) Headers(values map[string]string) OptionBuilder
( OptionBuilder) JSON(value any) OptionBuilder
( OptionBuilder) Middleware(mw ...req.RequestMiddleware) OptionBuilder
( OptionBuilder) OutputFile(path string) OptionBuilder
( OptionBuilder) Path(key string, value any) OptionBuilder
( OptionBuilder) Paths(values map[string]any) OptionBuilder
( OptionBuilder) Proxy(proxyURL string) OptionBuilder
( OptionBuilder) ProxyFunc(fn func(*http.Request) (*url.URL, error)) OptionBuilder
( OptionBuilder) Queries(values map[string]string) OptionBuilder
( OptionBuilder) Query(kv ...string) OptionBuilder
( OptionBuilder) Redirect(policies ...req.RedirectPolicy) OptionBuilder
( OptionBuilder) Retry(fn func(*req.Client)) OptionBuilder
( OptionBuilder) RetryBackoff(min, max time.Duration) OptionBuilder
( OptionBuilder) RetryCondition(condition req.RetryConditionFunc) OptionBuilder
( OptionBuilder) RetryCount(count int) OptionBuilder
( OptionBuilder) RetryFixedInterval(interval time.Duration) OptionBuilder
( OptionBuilder) RetryHook(hook req.RetryHookFunc) OptionBuilder
( OptionBuilder) RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder
( OptionBuilder) TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
( OptionBuilder) TLSFingerprintAndroid() OptionBuilder
( OptionBuilder) TLSFingerprintChrome() OptionBuilder
( OptionBuilder) TLSFingerprintEdge() OptionBuilder
( OptionBuilder) TLSFingerprintFirefox() OptionBuilder
( OptionBuilder) TLSFingerprintIOS() OptionBuilder
( OptionBuilder) TLSFingerprintRandomized() OptionBuilder
( OptionBuilder) TLSFingerprintSafari() OptionBuilder
( OptionBuilder) Timeout(d time.Duration) OptionBuilder
( OptionBuilder) Trace() OptionBuilder
( OptionBuilder) TraceAll() OptionBuilder
( OptionBuilder) Transport(rt http.RoundTripper) OptionBuilder
( OptionBuilder) UploadCallback(callback req.UploadCallback) OptionBuilder
( OptionBuilder) UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder
( OptionBuilder) UploadProgress() OptionBuilder
( OptionBuilder) UserAgent(value string) OptionBuilder
OptionBuilder : Option
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 Dump() 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 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 Timeout(d time.Duration) 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 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 OptionBuilder.AsChrome() OptionBuilder
func OptionBuilder.AsFirefox() OptionBuilder
func OptionBuilder.AsMobile() OptionBuilder
func OptionBuilder.AsSafari() OptionBuilder
func OptionBuilder.Auth(scheme, token string) OptionBuilder
func OptionBuilder.BaseURL(url string) OptionBuilder
func OptionBuilder.Basic(user, pass string) OptionBuilder
func OptionBuilder.Bearer(token string) OptionBuilder
func OptionBuilder.Before(fn func(*req.Request)) OptionBuilder
func OptionBuilder.Body(value any) OptionBuilder
func OptionBuilder.CookieJar(jar http.CookieJar) OptionBuilder
func OptionBuilder.Dump() OptionBuilder
func OptionBuilder.DumpAll() OptionBuilder
func OptionBuilder.DumpEachRequest() OptionBuilder
func OptionBuilder.DumpEachRequestTo(output io.Writer) OptionBuilder
func OptionBuilder.DumpTo(output io.Writer) OptionBuilder
func OptionBuilder.DumpToFile(filename string) OptionBuilder
func OptionBuilder.ErrorMapper(fn ErrorMapperFunc) OptionBuilder
func OptionBuilder.File(paramName, filePath string) OptionBuilder
func OptionBuilder.FileBytes(paramName, filename string, content []byte) OptionBuilder
func OptionBuilder.FileReader(paramName, filename string, reader io.Reader) OptionBuilder
func OptionBuilder.Files(files map[string]string) OptionBuilder
func OptionBuilder.Form(values map[string]string) OptionBuilder
func OptionBuilder.Header(key, value string) OptionBuilder
func OptionBuilder.Headers(values map[string]string) OptionBuilder
func OptionBuilder.JSON(value any) OptionBuilder
func OptionBuilder.Middleware(mw ...req.RequestMiddleware) OptionBuilder
func OptionBuilder.OutputFile(path string) OptionBuilder
func OptionBuilder.Path(key string, value any) OptionBuilder
func OptionBuilder.Paths(values map[string]any) OptionBuilder
func OptionBuilder.Proxy(proxyURL string) OptionBuilder
func OptionBuilder.ProxyFunc(fn func(*http.Request) (*url.URL, error)) OptionBuilder
func OptionBuilder.Queries(values map[string]string) OptionBuilder
func OptionBuilder.Query(kv ...string) OptionBuilder
func OptionBuilder.Redirect(policies ...req.RedirectPolicy) OptionBuilder
func OptionBuilder.Retry(fn func(*req.Client)) OptionBuilder
func OptionBuilder.RetryBackoff(min, max time.Duration) OptionBuilder
func OptionBuilder.RetryCondition(condition req.RetryConditionFunc) OptionBuilder
func OptionBuilder.RetryCount(count int) OptionBuilder
func OptionBuilder.RetryFixedInterval(interval time.Duration) OptionBuilder
func OptionBuilder.RetryHook(hook req.RetryHookFunc) OptionBuilder
func OptionBuilder.RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder
func OptionBuilder.Timeout(d time.Duration) OptionBuilder
func OptionBuilder.TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
func OptionBuilder.TLSFingerprintAndroid() OptionBuilder
func OptionBuilder.TLSFingerprintChrome() OptionBuilder
func OptionBuilder.TLSFingerprintEdge() OptionBuilder
func OptionBuilder.TLSFingerprintFirefox() OptionBuilder
func OptionBuilder.TLSFingerprintIOS() OptionBuilder
func OptionBuilder.TLSFingerprintRandomized() OptionBuilder
func OptionBuilder.TLSFingerprintSafari() OptionBuilder
func OptionBuilder.Trace() OptionBuilder
func OptionBuilder.TraceAll() OptionBuilder
func OptionBuilder.Transport(rt http.RoundTripper) OptionBuilder
func OptionBuilder.UploadCallback(callback req.UploadCallback) OptionBuilder
func OptionBuilder.UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder
func OptionBuilder.UploadProgress() OptionBuilder
func OptionBuilder.UserAgent(value string) OptionBuilder
Type Parameters:
T: any
Result contains the decoded response body and response metadata.
Body T
Err error
Response *req.Response
func Delete[T](client *Client, url string, opts ...Option) Result[T]
func DeleteCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Get[T](client *Client, url string, opts ...Option) Result[T]
func GetCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Head[T](client *Client, url string, opts ...Option) Result[T]
func HeadCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Options[T](client *Client, url string, opts ...Option) Result[T]
func OptionsCtx[T](client *Client, ctx context.Context, url string, opts ...Option) Result[T]
func Patch[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PatchCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
func Post[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PostCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
func Put[In, Out](client *Client, url string, body In, opts ...Option) Result[Out]
func PutCtx[In, Out](client *Client, ctx context.Context, url string, body In, opts ...Option) Result[Out]
TLSFingerprintKind selects a TLS fingerprint preset.
func TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
func OptionBuilder.TLSFingerprint(kind TLSFingerprintKind) OptionBuilder
const TLSFingerprintAndroidKind
const TLSFingerprintChromeKind
const TLSFingerprintEdgeKind
const TLSFingerprintFirefoxKind
const TLSFingerprintIOSKind
const TLSFingerprintRandomizedKind
const TLSFingerprintSafariKind
Package-Level Functions (total 74)
AsChrome applies the Chrome browser profile (headers, TLS, and HTTP/2 behavior).
@group Browser Profiles
Applies to client configuration only.
Example: use a Chrome profile
c := httpx.New(httpx.AsChrome())
_ = c
AsFirefox applies the Firefox browser profile (headers, TLS, and HTTP/2 behavior).
@group Browser Profiles
Applies to client configuration only.
Example: use a Firefox profile
c := httpx.New(httpx.AsFirefox())
_ = c
AsMobile applies a mobile Chrome-like profile (headers, TLS, and HTTP/2 behavior).
@group Browser Profiles
Applies to client configuration only.
Example: use a mobile profile
c := httpx.New(httpx.AsMobile())
_ = c
AsSafari applies the Safari browser profile (headers, TLS, and HTTP/2 behavior).
@group Browser Profiles
Applies to client configuration only.
Example: use a Safari profile
c := httpx.New(httpx.AsSafari())
_ = c
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 := httpx.New(httpx.Auth("Token", "abc123"))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.Auth("Token", "abc123"))
BaseURL sets a base URL on the client.
@group Client Options
Applies to client configuration only.
Example: client base URL
c := httpx.New(httpx.BaseURL("https://api.example.com"))
_ = c
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 := httpx.New(httpx.Basic("user", "pass"))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.Basic("user", "pass"))
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 := httpx.New(httpx.Bearer("token"))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.Bearer("token"))
Before runs a hook before the request is sent.
@group Request Control
Applies to individual requests only.
Example: mutate req.Request
c := httpx.New()
_ = httpx.Get[string](c, "https://example.com", httpx.Before(func(r *req.Request) {
r.EnableDump()
}))
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 := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com", nil, httpx.Body(Payload{Name: "Ana"}))
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://example.com")
jar.SetCookies(u, []*http.Cookie{
{Name: "session", Value: "abc123"},
})
c := httpx.New(httpx.CookieJar(jar))
_ = c
Default returns the shared default client.
@group Client
Example: use default client for quick calls
c := httpx.Default()
_ = c
Type Parameters:
T: any
Delete issues a DELETE request using the provided client.
@group Requests
Example: typed DELETE
type DeleteResponse struct {
OK bool `json:"ok"`
}
c := httpx.New()
res := httpx.Delete[DeleteResponse](c, "https://api.example.com/users/1")
_, _ = res.Body, res.Err // Body is DeleteResponse
Type Parameters:
T: any
DeleteCtx issues a DELETE request using the provided client and context.
@group Requests (Context)
Example: context-aware DELETE
type DeleteResponse struct {
OK bool `json:"ok"`
}
c := httpx.New()
ctx := context.Background()
res := httpx.DeleteCtx[DeleteResponse](c, ctx, "https://api.example.com/users/1")
_, _ = res.Body, res.Err // Body is DeleteResponse
Dump enables req's request-level dump output.
@group Debugging
Applies to individual requests only.
Example: dump a single request
c := httpx.New()
_ = httpx.Get[string](c, "https://example.com", httpx.Dump())
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 := httpx.New(httpx.DumpAll())
_ = c
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 := httpx.New(httpx.DumpEachRequest())
_ = c
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 := httpx.New(httpx.DumpEachRequestTo(&buf))
_ = httpx.Get[string](c, "https://example.com")
_ = buf.String()
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 := httpx.New()
_ = httpx.Get[string](c, "https://example.com", httpx.DumpTo(&buf))
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 := httpx.New()
_ = httpx.Get[string](c, "https://example.com", httpx.DumpToFile("httpx.dump"))
ErrorMapper sets a custom error mapper for non-2xx responses.
@group Client Options
Applies only to the client configuration.
Example: map error responses
c := httpx.New(httpx.ErrorMapper(func(resp *req.Response) error {
return fmt.Errorf("status %d", resp.StatusCode)
}))
_ = c
File attaches a file from disk as multipart form data.
@group Upload Options
Applies to individual requests only.
Example: upload a file
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil, httpx.File("file", "/tmp/report.txt"))
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 := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil, httpx.FileBytes("file", "report.txt", []byte("hello")))
FileReader attaches a file from a reader as multipart form data.
@group Upload Options
Applies to individual requests only.
Example: upload from reader
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil, httpx.FileReader("file", "report.txt", strings.NewReader("hello")))
Files attaches multiple files from disk as multipart form data.
@group Upload Options
Applies to individual requests only.
Example: upload multiple files
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil, httpx.Files(map[string]string{
"fileA": "/tmp/a.txt",
"fileB": "/tmp/b.txt",
}))
Form sets form data for the request.
@group Request Composition
Applies to individual requests only.
Example: submit a form
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com", nil, httpx.Form(map[string]string{
"name": "Ana",
}))
Type Parameters:
T: any
Get issues a GET request using the provided client.
@group Requests
Example: fetch GitHub pull requests (typed)
type PullRequest struct {
Number int `json:"number"`
Title string `json:"title"`
}
c := httpx.New(httpx.Header("Accept", "application/vnd.github+json"))
res := httpx.Get[[]PullRequest](c, "https://api.github.com/repos/goforj/httpx/pulls")
if res.Err != nil {
return
}
godump.Dump(res.Body)
Example: bind to a string body
c2 := httpx.New()
res2 := httpx.Get[string](c2, "https://httpbin.org/uuid")
_, _ = res2.Body, res2.Err // Body is string
Type Parameters:
T: any
GetCtx issues a GET request using the provided client and context.
@group Requests (Context)
Example: context-aware GET
type User struct {
Name string `json:"name"`
}
c := httpx.New()
ctx := context.Background()
res := httpx.GetCtx[User](c, ctx, "https://api.example.com/users/1")
_, _ = res.Body, res.Err // Body is User
Type Parameters:
T: any
Head issues a HEAD request using the provided client.
@group Requests
Example: HEAD request
c := httpx.New()
res := httpx.Head[string](c, "https://example.com")
_ = res
Type Parameters:
T: any
HeadCtx issues a HEAD request using the provided client and context.
@group Requests (Context)
Example: context-aware HEAD
c := httpx.New()
ctx := context.Background()
res := httpx.HeadCtx[string](c, ctx, "https://example.com")
_ = res
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 := httpx.New(httpx.Header("X-Trace", "1"))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.Header("X-Trace", "1"))
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 := httpx.New(httpx.Headers(map[string]string{
"X-Trace": "1",
"Accept": "application/json",
}))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.Headers(map[string]string{
"X-Trace": "1",
"Accept": "application/json",
}))
JSON sets the request body as JSON.
@group Request Composition
Applies to individual requests only.
Example: force JSON body
type Payload struct {
Name string `json:"name"`
}
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com", nil, httpx.JSON(Payload{Name: "Ana"}))
Middleware adds request middleware to the client.
@group Client Options
Applies only to the client configuration.
Example: add request middleware
c := httpx.New(httpx.Middleware(func(_ *req.Client, r *req.Request) error {
r.SetHeader("X-Trace", "1")
return nil
}))
_ = c
New creates a client with opinionated defaults and optional overrides.
@group Client
Example: configure all client options
var buf bytes.Buffer
c := httpx.New(httpx.
BaseURL("https://api.example.com").
Timeout(5*time.Second).
Header("X-Trace", "1").
Headers(map[string]string{
"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) {}),
)
_ = c
Type Parameters:
T: any
Options issues an OPTIONS request using the provided client.
@group Requests
Example: OPTIONS request
c := httpx.New()
res := httpx.Options[string](c, "https://example.com")
_ = res
Type Parameters:
T: any
OptionsCtx issues an OPTIONS request using the provided client and context.
@group Requests (Context)
Example: context-aware OPTIONS
c := httpx.New()
ctx := context.Background()
res := httpx.OptionsCtx[string](c, ctx, "https://example.com")
_ = res
OutputFile streams the response body to a file path.
@group Download Options
Applies to individual requests only.
Example: download to file
c := httpx.New()
_ = httpx.Get[string](c, "https://example.com/file", httpx.OutputFile("/tmp/file.bin"))
Type Parameters:
In: any
Out: any
Patch issues a PATCH request using the provided client.
@group Requests
Example: typed PATCH
type UpdateUser struct {
Name string `json:"name"`
}
type User struct {
Name string `json:"name"`
}
c := httpx.New()
res := httpx.Patch[UpdateUser, User](c, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
_, _ = res.Body, res.Err // Body is User
Type Parameters:
In: any
Out: any
PatchCtx issues a PATCH request using the provided client and context.
@group Requests (Context)
Example: context-aware PATCH
type UpdateUser struct {
Name string `json:"name"`
}
type User struct {
Name string `json:"name"`
}
c := httpx.New()
ctx := context.Background()
res := httpx.PatchCtx[UpdateUser, User](c, ctx, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
_, _ = res.Body, res.Err // Body is User
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 := httpx.New()
_ = httpx.Get[User](c, "https://example.com/users/{id}", httpx.Path("id", 42))
Paths sets multiple path parameters.
@group Request Composition
Applies to individual requests only.
Example: multiple path parameters
type User struct {
Name string `json:"name"`
}
c := httpx.New()
_ = httpx.Get[User](c, "https://example.com/orgs/{org}/users/{id}", httpx.Paths(map[string]any{
"org": "goforj",
"id": 42,
}))
Type Parameters:
In: any
Out: any
Post issues a POST request using the provided client.
@group Requests
Example: typed POST
type CreateUser struct {
Name string `json:"name"`
}
type User struct {
Name string `json:"name"`
}
c := httpx.New()
res := httpx.Post[CreateUser, User](c, "https://api.example.com/users", CreateUser{Name: "Ana"})
_, _ = res.Body, res.Err // Body is User
Type Parameters:
In: any
Out: any
PostCtx issues a POST request using the provided client and context.
@group Requests (Context)
Example: context-aware POST
type CreateUser struct {
Name string `json:"name"`
}
type User struct {
Name string `json:"name"`
}
c := httpx.New()
ctx := context.Background()
res := httpx.PostCtx[CreateUser, User](c, ctx, "https://api.example.com/users", CreateUser{Name: "Ana"})
_, _ = res.Body, res.Err // Body is User
Proxy sets a proxy URL for the client.
@group Client Options
Applies to client configuration only.
Example: set proxy URL
c := httpx.New(httpx.Proxy("http://localhost:8080"))
_ = c
ProxyFunc sets a proxy function for the client.
@group Client Options
Applies to client configuration only.
Example: set proxy function
c := httpx.New(httpx.ProxyFunc(http.ProxyFromEnvironment))
_ = c
Type Parameters:
In: any
Out: any
Put issues a PUT request using the provided client.
@group Requests
Example: typed PUT
type UpdateUser struct {
Name string `json:"name"`
}
type User struct {
Name string `json:"name"`
}
c := httpx.New()
res := httpx.Put[UpdateUser, User](c, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
_, _ = res.Body, res.Err // Body is User
Type Parameters:
In: any
Out: any
PutCtx issues a PUT request using the provided client and context.
@group Requests (Context)
Example: context-aware PUT
type UpdateUser struct {
Name string `json:"name"`
}
type User struct {
Name string `json:"name"`
}
c := httpx.New()
ctx := context.Background()
res := httpx.PutCtx[UpdateUser, User](c, ctx, "https://api.example.com/users/1", UpdateUser{Name: "Ana"})
_, _ = res.Body, res.Err // Body is User
Queries adds multiple query parameters.
@group Request Composition
Applies to individual requests only.
Example: add query params
c := httpx.New()
_ = httpx.Get[string](c, "https://example.com/search", httpx.Queries(map[string]string{
"q": "go",
"ok": "1",
}))
Query adds query parameters as key/value pairs.
@group Request Composition
Applies to individual requests only.
Example: add query params
c := httpx.New()
_ = httpx.Get[string](c, "https://example.com/search", httpx.Query("q", "go", "ok", "1"))
Redirect sets the redirect policy for the client.
@group Client Options
Applies to client configuration only.
Example: disable redirects
c := httpx.New(httpx.Redirect(req.NoRedirectPolicy()))
_ = c
Retry applies a custom retry configuration to the client.
@group Retry (Client)
Applies only to client configuration.
Example: configure client retry
c := httpx.New(httpx.Retry(func(rc *req.Client) {
rc.SetCommonRetryCount(2)
}))
_ = c
RetryBackoff sets a capped exponential backoff retry interval for a request.
@group Retry
Applies to both client defaults and individual requests.
Example: retry backoff
// Apply to all requests
c := httpx.New(httpx.RetryBackoff(100*time.Millisecond, 2*time.Second))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.RetryBackoff(100*time.Millisecond, 2*time.Second))
RetryCondition sets the retry condition for a request.
@group Retry
Applies to both client defaults and individual requests.
Example: retry on 503
// Apply to all requests
c := httpx.New(httpx.RetryCondition(func(resp *req.Response, _ error) bool {
return resp != nil && resp.StatusCode == 503
}))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.RetryCondition(func(resp *req.Response, _ error) bool {
return resp != nil && resp.StatusCode == 503
}))
RetryCount enables retry for a request and sets the maximum retry count.
@group Retry
Applies to both client defaults and individual requests.
Example: retry count
// Apply to all requests
c := httpx.New(httpx.RetryCount(2))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.RetryCount(2))
RetryFixedInterval sets a fixed retry interval for a request.
@group Retry
Applies to both client defaults and individual requests.
Example: retry interval
// Apply to all requests
c := httpx.New(httpx.RetryFixedInterval(200 * time.Millisecond))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.RetryFixedInterval(200*time.Millisecond))
RetryHook registers a retry hook for a request.
@group Retry
Applies to both client defaults and individual requests.
Example: hook on retry
// Apply to all requests
c := httpx.New(httpx.RetryHook(func(_ *req.Response, _ error) {}))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.RetryHook(func(_ *req.Response, _ error) {}))
RetryInterval sets a custom retry interval function for a request.
@group Retry
Applies to both client defaults and individual requests.
Example: custom retry interval
// Apply to all requests
c := httpx.New(httpx.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
return time.Duration(attempt) * 100 * time.Millisecond
}))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
return time.Duration(attempt) * 100 * time.Millisecond
}))
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 := httpx.New(httpx.Timeout(2 * time.Second))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.Timeout(2*time.Second))
TLSFingerprint applies a TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply a TLS fingerprint preset
c := httpx.New(httpx.TLSFingerprint(httpx.TLSFingerprintChromeKind))
_ = c
TLSFingerprintAndroid applies the Android TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply Android TLS fingerprint
c := httpx.New(httpx.TLSFingerprintAndroid())
_ = c
TLSFingerprintChrome applies the Chrome TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply Chrome TLS fingerprint
c := httpx.New(httpx.TLSFingerprintChrome())
_ = c
TLSFingerprintEdge applies the Edge TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply Edge TLS fingerprint
c := httpx.New(httpx.TLSFingerprintEdge())
_ = c
TLSFingerprintFirefox applies the Firefox TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply Firefox TLS fingerprint
c := httpx.New(httpx.TLSFingerprintFirefox())
_ = c
TLSFingerprintIOS applies the iOS TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply iOS TLS fingerprint
c := httpx.New(httpx.TLSFingerprintIOS())
_ = c
TLSFingerprintRandomized applies a randomized TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply randomized TLS fingerprint
c := httpx.New(httpx.TLSFingerprintRandomized())
_ = c
TLSFingerprintSafari applies the Safari TLS fingerprint preset.
@group Advanced
Applies to client configuration only.
Example: apply Safari TLS fingerprint
c := httpx.New(httpx.TLSFingerprintSafari())
_ = c
Trace enables req's request-level trace output.
@group Debugging
Applies to individual requests only.
Example: trace a single request
c := httpx.New()
_ = httpx.Get[string](c, "https://example.com", httpx.Trace())
TraceAll enables req's client-level trace output for all requests.
@group Debugging
Applies to the client configuration only.
Example: trace all requests
c := httpx.New(httpx.TraceAll())
_ = c
Transport wraps the underlying transport with a custom RoundTripper.
@group Client Options
Applies to client configuration only.
Example: wrap transport
c := httpx.New(httpx.Transport(http.RoundTripper(http.DefaultTransport)))
_ = c
UploadCallback registers a callback for upload progress.
@group Upload Options
Applies to individual requests only.
Example: track upload progress
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil,
httpx.File("file", "/tmp/report.bin"),
httpx.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")
}
}),
)
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 := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil,
httpx.File("file", "/tmp/report.bin"),
httpx.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),
)
UploadProgress enables a default progress spinner and bar for uploads.
@group Upload Options
Applies to individual requests only.
Example: upload with automatic progress
c := httpx.New()
_ = httpx.Post[any, string](c, "https://example.com/upload", nil,
httpx.File("file", "/tmp/report.bin"),
httpx.UploadProgress(),
)
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 := httpx.New(httpx.UserAgent("my-app/1.0"))
httpx.Get[string](c, "https://example.com")
// Apply to a single request
httpx.Get[string](httpx.Default(), "https://example.com", httpx.UserAgent("my-app/1.0"))
Package-Level Constants (total 7)
const TLSFingerprintAndroidKind TLSFingerprintKind = 4 const TLSFingerprintChromeKind TLSFingerprintKind = 0 const TLSFingerprintEdgeKind TLSFingerprintKind = 3 const TLSFingerprintFirefoxKind TLSFingerprintKind = 1 const TLSFingerprintIOSKind TLSFingerprintKind = 5 const TLSFingerprintSafariKind TLSFingerprintKind = 2
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |