httpclient

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httpclient

Send HTTP requests, decode responses into Go types, and configure retries and authentication. httpclient uses req for transport and exposes the underlying request and client when you need them.

Go Reference Go Test Security Go version Latest version Published GitHub release count Coverage Tests

Installation · Quick Start · Debugging · API

Installation

From a Go module with Go 1.27 or newer, run the install command.

go get github.com/goforj/httpclient

Quick Start

Use Client.Get to fetch a public GitHub repository and decode its JSON response into a Go struct. Save the example as main.go in your module and run go run ..

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/goforj/httpclient"
)

// Repository holds the repository name returned by GitHub.
type Repository struct {
	FullName string `json:"full_name"`
}

// main fetches the httpclient repository from the public GitHub API.
func main() {
	client := httpclient.New()
	repo, err := client.Get[Repository](context.Background(), "https://api.github.com/repos/goforj/httpclient")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(repo.FullName)
	// goforj/httpclient
}

From the repository root, run go run ./examples/quick-start. The program prints goforj/httpclient.

Status and Headers

Typed requests such as Client.Get[T] return an HTTPError by default for statuses outside 2xx. Use errors.As to inspect its status code, headers, and body.

Use Client.Send when you need to handle the response directly, such as a conditional request that returns 304. It returns an *http.Response as soon as the headers arrive. Close the response body when you finish reading it.

Context and Retries

Pass the caller's context as the first argument to each request. Use context.WithTimeout to bound the whole operation, including retries and the time between them. The client Timeout applies to each HTTP attempt.

Set RetryCount to enable retries on transport errors. To retry an HTTP status, also set a RetryCondition. Pass the options to New for client defaults or to a request method for a single call. On 429 and 503, a valid Retry-After can extend the configured delay. When that delay would exceed the context deadline, the client returns the last response. Canceling the context interrupts the wait.

Testing

Pass an httpclienttest.Transport to httpclient.Transport to exercise your real client configuration without a server. Register replies by HTTP method and request URI or absolute URL. Each request consumes the next reply. The transport reports ErrUnexpectedRequest when a request has no reply and records the method, URL, headers, and body for assertions.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"

	"github.com/goforj/httpclient"
	"github.com/goforj/httpclient/httpclienttest"
)

// main demonstrates recording and retrying a request without a running server.
func main() {
	var transport httpclienttest.Transport
	transport.Respond(http.MethodGet, "/orders/42",
		httpclienttest.Response{Err: errors.New("temporary connection failure")},
		httpclienttest.Response{
			Header: http.Header{"Content-Type": {"application/json"}},
			Body:   []byte(`{"state":"shipped"}`),
		},
	)

	client := httpclient.New(
		httpclient.BaseURL("https://api.example.test"),
		httpclient.Bearer("test-token"),
		httpclient.Transport(&transport),
		httpclient.RetryCount(1).RetryFixedInterval(0),
	)
	type Order struct {
		State string `json:"state"`
	}
	order, err := client.Get[Order](context.Background(), "/orders/42")
	if err != nil {
		log.Fatal(err)
	}

	requests := transport.Requests()
	fmt.Printf("%s after %d requests (%s)\n", order.State, len(requests), requests[0].Header.Get("Authorization"))
	// shipped after 2 requests (Bearer test-token)
}

From the repository root, run go run ./examples/testing.

Debugging and Tracing

Pass httpclient.EnableDump() to dump a single request and its response. Use httpclient.DumpEachRequest() to dump every request and response on a client.

Setting HTTP_TRACE to any value enables request and response dumps for newly created clients. Unset it before creating a client to disable environment-controlled dumps. Dumps include headers and bodies, which can contain credentials and other private data.

Development

Run make test and make vet from the repository root. After changing GoDoc examples or the examples embedded above, run make generate to refresh the README and example programs.

The test suite compiles the example programs. It also runs the retry, error handling, and testing examples against the recording transport and checks their output.

See the migration guide for switching to client methods and migrating from Httpx.

API Index

Group Functions
Auth Auth · Basic · Bearer
Browser Profiles AsChrome · AsFirefox · AsMobile · AsSafari
Client Client.Raw · Client.Req · Default · New
Client Options BaseURL · CookieJar · ErrorMapper · Middleware · Proxy · ProxyFunc · Redirect · Transport
Debugging Dump · DumpAll · DumpEachRequest · DumpEachRequestTo · DumpTo · DumpToFile · EnableDump · OptionBuilder.DumpToFile · Trace · TraceAll
Download Options OutputFile
Errors HTTPError.Error
Request Composition Body · Form · Header · Headers · JSON · Path · Paths · Queries · Query · UserAgent
Request Control Before · Timeout
Requests Client.Delete · Client.Get · Client.Head · Client.Options · Client.Patch · Client.Post · Client.Put · Client.Send · Do
Retry RetryBackoff · RetryCondition · RetryCount · RetryFixedInterval · RetryHook · RetryInterval
Retry (Client) Retry
Upload Options File · FileBytes · FileReader · Files · UploadCallback · UploadCallbackWithInterval · UploadProgress

Auth

Auth

Auth sets the Authorization header using a scheme and token.

// Apply to all requests
c := httpclient.New(httpclient.Auth("Token", "abc123"))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Token abc123" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Auth("Token", "abc123"))
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Token abc123" #string
//   }
// }

Basic

Basic sets HTTP basic authentication headers.

// Apply to all requests
c := httpclient.New(httpclient.Basic("user", "pass"))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Basic dXNlcjpwYXNz" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Basic("user", "pass"))
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Basic dXNlcjpwYXNz" #string
//   }
// }

Bearer

Bearer sets the Authorization header with a bearer token.

// Apply to all requests
c := httpclient.New(httpclient.Bearer("token"))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Bearer token" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Bearer("token"))
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Bearer token" #string
//   }
// }

Browser Profiles

Use TLSFingerprint to select a browser, mobile, or randomized TLS preset. Go reference

AsChrome

AsChrome applies the Chrome browser profile (headers including User-Agent, TLS, and HTTP/2 behavior).

_ = httpclient.New(httpclient.AsChrome())

AsFirefox

AsFirefox applies the Firefox browser profile (headers including User-Agent, TLS, and HTTP/2 behavior).

c := httpclient.New(httpclient.AsFirefox())
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     User-Agent => "<user-agent>" #string
//   }
// }

AsMobile

AsMobile applies a mobile Chrome-like profile (headers including User-Agent, TLS, and HTTP/2 behavior).

_ = httpclient.New(httpclient.AsMobile())

AsSafari

AsSafari applies the Safari browser profile (headers including User-Agent, TLS, and HTTP/2 behavior).

_ = httpclient.New(httpclient.AsSafari())

Client

Client.Raw

Raw returns the underlying req client for chaining raw requests.

Client.Req

Req returns the underlying req client for advanced usage.

Default

Default returns the shared default client.

New

New creates a reusable client with optional defaults for each request.

_ = httpclient.New(
	httpclient.BaseURL("https://api.github.com"),
	httpclient.Timeout(5*time.Second),
)

Client Options

BaseURL

BaseURL sets a base URL on the client.

c := httpclient.New(httpclient.BaseURL("https://httpbin.org"))
res, _ := c.Get[map[string]any](context.Background(), "/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

CookieJar

CookieJar sets the cookie jar for the client.

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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/cookies")
httpclient.Dump(res)
// #map[string]interface {} {
//   cookies => #map[string]interface {} {
//     session => "abc123" #string
//   }
// }

ErrorMapper

ErrorMapper sets a custom error mapper for non-2xx responses.

var transport httpclienttest.Transport
transport.Respond(http.MethodGet, "/orders/42",
	httpclienttest.Response{StatusCode: http.StatusInternalServerError},
)
client := httpclient.New(
	httpclient.BaseURL("https://api.example.test"),
	httpclient.Transport(&transport),
	httpclient.ErrorMapper(func(resp *req.Response) error {
		return fmt.Errorf("orders API returned status %d", resp.StatusCode)
	}),
)
_, err := client.Get[string](context.Background(), "/orders/42")
fmt.Println(err)
// orders API returned status 500

Middleware

Middleware adds request middleware to the client.

c := httpclient.New(httpclient.Middleware(func(_ *req.Client, r *req.Request) error {
	r.SetHeader("X-Trace", "1")
	return nil
}))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }

Proxy

Proxy sets a proxy URL for the client. Use a URL for a proxy you can reach.

_ = httpclient.New(httpclient.Proxy("http://localhost:8080"))

ProxyFunc

ProxyFunc selects a proxy for each request. Pass http.ProxyFromEnvironment to use the HTTP proxy settings in the environment.

_ = httpclient.New(httpclient.ProxyFunc(http.ProxyFromEnvironment))

Redirect

Redirect sets the redirect policy for the client.

c := httpclient.New(httpclient.Redirect(req.NoRedirectPolicy()))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/redirect/1")
httpclient.Dump(res)
// map[string]interface {}(nil)

Transport

Transport wraps the underlying transport with a custom RoundTripper.

c := httpclient.New(httpclient.Transport(http.RoundTripper(http.DefaultTransport)))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

Debugging

Dump

Dump prints values using the bundled godump formatter.

res, _ := httpclient.Default().Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

DumpAll

DumpAll enables req's client-level dump output for all requests.

c := httpclient.New(httpclient.DumpAll())
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

DumpEachRequest

DumpEachRequest enables request-level dumps for each request on the client.

c := httpclient.New(httpclient.DumpEachRequest())
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

DumpEachRequestTo

DumpEachRequestTo enables request-level dumps for each request and writes them to the provided output.

var buf bytes.Buffer
c := httpclient.New(httpclient.DumpEachRequestTo(&buf))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }
_ = buf.String()

DumpTo

DumpTo enables req's request-level dump output to a writer.

var buf bytes.Buffer
c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.DumpTo(&buf))
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

DumpToFile

DumpToFile enables req's request-level dump output to a file path.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.DumpToFile("httpclient.dump"))
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

EnableDump

EnableDump enables req's request-level dump output.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.EnableDump())
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

OptionBuilder.DumpToFile

DumpToFile configures file output for one request and releases the file after each write.

Trace

Trace enables req's request-level trace output.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.Trace())
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

TraceAll

TraceAll enables req's client-level trace output for all requests.

c := httpclient.New(httpclient.TraceAll())
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

Download Options

OutputFile

OutputFile streams the response body to a file path.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/bytes/1024", httpclient.OutputFile("/tmp/file.bin"))
httpclient.Dump(res)
// map[string]interface {}(nil)

Errors

HTTPError.Error

Error returns a short, human-friendly summary of the HTTP error.

var transport httpclienttest.Transport
transport.Respond(http.MethodGet, "/orders/42",
	httpclienttest.Response{StatusCode: http.StatusNotFound},
)
client := httpclient.New(
	httpclient.BaseURL("https://api.example.test"),
	httpclient.Transport(&transport),
)
_, err := client.Get[string](context.Background(), "/orders/42")
var httpErr *httpclient.HTTPError
if !errors.As(err, &httpErr) {
	log.Fatalf("expected an HTTP error, got %v", err)
}
fmt.Println(httpErr.StatusCode)
// 404

Request Composition

Body

Body sets the request body and infers JSON for structs and maps.

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

c := httpclient.New()
res, _ := c.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil, httpclient.Body(Payload{Name: "Ana"}))
httpclient.Dump(res)
// #map[string]interface {} {
//   json => #map[string]interface {} {
//     name => "Ana" #string
//   }
// }

Form

Form sets form data for the request.

c := httpclient.New()
res, _ := c.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil, httpclient.Form(map[string]string{
	"name": "alice",
}))
httpclient.Dump(res)
// #map[string]interface {} {
//   form => #map[string]interface {} {
//     name => "alice" #string
//   }
// }

Header

Header sets a header on a request or client.

// Apply to all requests
c := httpclient.New(httpclient.Header("X-Trace", "1"))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Header("X-Trace", "1"))
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }

Headers

Headers sets multiple headers on a request or client.

// Apply to all requests
c := httpclient.New(httpclient.Headers(map[string]string{
	"X-Trace": "1",
	"Accept":  "application/json",
}))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Accept => "application/json" #string
//     X-Trace => "1" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Headers(map[string]string{
	"X-Trace": "1",
	"Accept":  "application/json",
}))
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Accept => "application/json" #string
//     X-Trace => "1" #string
//   }
// }

JSON

JSON forces JSON encoding for the request body (even when inference might choose differently).

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

c := httpclient.New()
res, _ := c.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil, httpclient.JSON(Payload{Name: "Ana"}))
httpclient.Dump(res)
// #map[string]interface {} {
//   json => #map[string]interface {} {
//     name => "Ana" #string
//   }
// }

Path

Path sets a path parameter by name.

type User struct {
	Name string `json:"name"`
}

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/anything/{id}", httpclient.Path("id", 42))
httpclient.Dump(res)
// #map[string]interface {} {
//   url => "https://httpbin.org/anything/42" #string
// }

Paths

Paths sets multiple path parameters from a map.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/anything/{org}/users/{id}", httpclient.Paths(map[string]any{
	"org": "goforj",
	"id":  7,
}))
httpclient.Dump(res)
// #map[string]interface {} {
//   url => "https://httpbin.org/anything/goforj/users/7" #string
// }

Queries

Queries sets query parameters from a map.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/get", httpclient.Queries(map[string]string{
	"q":  "search",
	"ok": "1",
}))
httpclient.Dump(res)
// #map[string]interface {} {
//   args => #map[string]interface {} {
//     ok => "1" #string
//     q => "search" #string
//   }
// }

Query

Query adds query parameters as key/value pairs.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/get", httpclient.Query("q", "search"))
httpclient.Dump(res)
// #map[string]interface {} {
//   args => #map[string]interface {} {
//     q => "search" #string
//   }
// }

UserAgent

UserAgent sets the User-Agent header on a request or client.

// Apply to all requests
c := httpclient.New(httpclient.UserAgent("my-app/1.0"))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     User-Agent => "my-app/1.0" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.UserAgent("my-app/1.0"))
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     User-Agent => "my-app/1.0" #string
//   }
// }

Request Control

Before

Before runs a hook before the request is sent.

c := httpclient.New()
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/get", httpclient.Before(func(r *req.Request) {
	r.EnableDump()
}))
httpclient.Dump(res)
// #map[string]interface {} {
//   url => "https://httpbin.org/get" #string
// }

Timeout

Timeout sets the timeout for each HTTP attempt, including reading the response body.

// Apply to all requests
c := httpclient.New(httpclient.Timeout(2 * time.Second))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/delay/2")
httpclient.Dump(res)
// map[string]interface {}(nil)

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/delay/2", httpclient.Timeout(2*time.Second))
httpclient.Dump(res)
// map[string]interface {}(nil)

Requests

Client.Delete

Delete issues a DELETE request and decodes its response.

type DeleteResponse struct {
	URL string `json:"url"`
}

c := httpclient.New()
res, err := c.Delete[DeleteResponse](context.Background(), "https://httpbin.org/delete")
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.DeleteResponse {
//   +URL => "https://httpbin.org/delete" #string
// }

Client.Get

Get issues a GET request and decodes its response.

Example: bind to a struct

type GetResponse struct {
	URL string `json:"url"`
}

c := httpclient.New()
res, err := c.Get[GetResponse](context.Background(), "https://httpbin.org/get")
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.GetResponse {
//   +URL => "https://httpbin.org/get" #string
// }

Example: read a string body using the same client

resString, err := c.Get[string](context.Background(), "https://httpbin.org/base64/aGVsbG8=")
if err != nil {
	log.Fatal(err)
}
fmt.Println(resString)
// hello

Client.Head

Head issues a HEAD request. A successful HEAD response has an empty body.

c := httpclient.New()
body, err := c.Head[string](context.Background(), "https://httpbin.org/get")
if err != nil {
	log.Fatal(err)
}
fmt.Println(len(body))
// 0

Client.Options

Options issues an OPTIONS request and decodes its response.

c := httpclient.New()
body, err := c.Options[string](context.Background(), "https://httpbin.org/get")
if err != nil {
	log.Fatal(err)
}
fmt.Println(len(body))
// 0

Client.Patch

Patch issues a PATCH request and decodes its response.

type UpdateUser struct {
	Name string `json:"name"`
}
type UpdateUserResponse struct {
	JSON UpdateUser `json:"json"`
}

c := httpclient.New()
res, err := c.Patch[UpdateUserResponse](context.Background(), "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.UpdateUserResponse {
//   +JSON   => #main.UpdateUser {
//     +Name => "Ana" #string
//   }
// }

Client.Post

Post issues a POST request and decodes its response.

type CreateUser struct {
	Name string `json:"name"`
}
type CreateUserResponse struct {
	JSON CreateUser `json:"json"`
}

c := httpclient.New()
res, err := c.Post[CreateUserResponse](context.Background(), "https://httpbin.org/post", CreateUser{Name: "Ana"})
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.CreateUserResponse {
//   +JSON   => #main.CreateUser {
//     +Name => "Ana" #string
//   }
// }

Client.Put

Put issues a PUT request and decodes its response.

type UpdateUser struct {
	Name string `json:"name"`
}
type UpdateUserResponse struct {
	JSON UpdateUser `json:"json"`
}

c := httpclient.New()
res, err := c.Put[UpdateUserResponse](context.Background(), "https://httpbin.org/put", UpdateUser{Name: "Ana"})
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.UpdateUserResponse {
//   +JSON   => #main.UpdateUser {
//     +Name => "Ana" #string
//   }
// }

Client.Send

Send returns the HTTP response when its headers arrive. Every HTTP status is returned as a response. The caller must close its body. Use Body, JSON, or Form to attach request data.

c := httpclient.New()
res, err := c.Send(context.Background(), http.MethodGet, "https://httpbin.org/get")
if err != nil {
	return
}
defer res.Body.Close()
fmt.Println(res.StatusCode)
// 200

Do

Do executes a pre-configured req request and returns the decoded body and response. The caller context controls cancellation and deadlines. Values added to the request during setup remain available.

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](context.Background(), r)
if err != nil {
	return
}
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }
println(rawResp.StatusCode)

Retry

RetryBackoff

RetryBackoff sets a capped exponential backoff with jitter between retry attempts.

_ = httpclient.New(httpclient.RetryCount(2).RetryBackoff(100*time.Millisecond, 2*time.Second))

RetryCondition

RetryCondition replaces the default retry condition for a request. Set RetryCount to enable retries. A transport failure can leave the HTTP response absent.

var transport httpclienttest.Transport
transport.Respond(http.MethodGet, "/orders/42",
	httpclienttest.Response{StatusCode: http.StatusServiceUnavailable},
	httpclienttest.Response{Body: []byte("shipped")},
)
client := httpclient.New(
	httpclient.BaseURL("https://api.example.test"),
	httpclient.Transport(&transport),
	httpclient.RetryCount(1),
	httpclient.RetryFixedInterval(0),
	httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
		return resp != nil && resp.Response != nil && resp.StatusCode == http.StatusServiceUnavailable
	}),
)
body, err := client.Get[string](context.Background(), "/orders/42")
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%s after %d attempts\n", body, len(transport.Requests()))
// shipped after 2 attempts

RetryCount

RetryCount sets the maximum number of retries after the first attempt. It defaults to zero. With retries enabled, the default policy retries transport errors with a fixed 100ms delay.

_ = httpclient.New(httpclient.RetryCount(2))

RetryFixedInterval

RetryFixedInterval sets the delay between retry attempts.

_ = httpclient.New(httpclient.RetryCount(2).RetryFixedInterval(200*time.Millisecond))

RetryHook

RetryHook registers a callback that runs before each retry attempt.

_ = httpclient.New(httpclient.RetryCount(2).RetryHook(func(_ *req.Response, err error) {
	fmt.Printf("retrying after %v\n", err)
}))

RetryInterval

RetryInterval sets a function that computes the delay before each retry.

_ = httpclient.New(httpclient.RetryCount(2).RetryInterval(func(_ *req.Response, attempt int) time.Duration {
	return time.Duration(attempt) * 100 * time.Millisecond
}))

Retry (Client)

Retry

Retry applies a custom retry configuration to the client. Defaults remain in effect unless the callback modifies them.

_ = httpclient.New(httpclient.Retry(func(rc *req.Client) {
	rc.SetCommonRetryCount(2)
}))

Upload Options

File

File attaches a file from disk as multipart form data.

dir, err := os.MkdirTemp("", "httpclient-upload-")
if err != nil {
	log.Print(err)
	return
}
defer os.RemoveAll(dir)

path := filepath.Join(dir, "report.txt")
if err := os.WriteFile(path, []byte("hello"), 0o600); err != nil {
	log.Print(err)
	return
}

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.File("file", path),
)
if err != nil {
	log.Print(err)
	return
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

FileBytes

FileBytes attaches a file from bytes as multipart form data.

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

FileReader

FileReader attaches a file from a reader as multipart form data.

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileReader("file", "report.txt", strings.NewReader("hello")),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

Files

Files attaches multiple files from disk as multipart form data.

dir, err := os.MkdirTemp("", "httpclient-upload-")
if err != nil {
	log.Print(err)
	return
}
defer os.RemoveAll(dir)

first := filepath.Join(dir, "a.txt")
second := filepath.Join(dir, "b.txt")
if err := os.WriteFile(first, []byte("hello"), 0o600); err != nil {
	log.Print(err)
	return
}
if err := os.WriteFile(second, []byte("world"), 0o600); err != nil {
	log.Print(err)
	return
}

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.Files(map[string]string{
		"fileA": first,
		"fileB": second,
	}),
)
if err != nil {
	log.Print(err)
	return
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    fileA => "hello" #string
//    fileB => "world" #string
// }

UploadCallback

UploadCallback registers a callback for upload progress.

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	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")
		}
	}),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

UploadCallbackWithInterval

UploadCallbackWithInterval registers a callback for upload progress with a minimum interval.

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	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),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

UploadProgress

UploadProgress enables a default progress spinner and bar for uploads.

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	httpclient.UploadProgress(),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

Documentation

Overview

Package httpclient sends HTTP requests and decodes responses into Go values.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

func Do[T any](ctx context.Context, r *req.Request) (T, *req.Response, error)

Do executes a pre-configured req request and returns the decoded body and response. The caller context controls cancellation and deadlines. Values added to the request during setup remain available. @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](context.Background(), r)
if err != nil {
	return
}
httpclient.Dump(res)
// #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.Default().Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #map[string]interface {} {
//   uuid => "<uuid>" #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 Default

func Default() *Client

Default returns the shared default client. @group Client

func New

func New(opts ...Option) *Client

New creates a reusable client with optional defaults for each request. @group Client

Example: configure a base URL and timeout

_ = httpclient.New(
	httpclient.BaseURL("https://api.github.com"),
	httpclient.Timeout(5*time.Second),
)

func (*Client) Delete

func (c *Client) Delete[Out any](ctx context.Context, url string, opts ...Option) (Out, error)

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](context.Background(), "https://httpbin.org/delete")
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.DeleteResponse {
//   +URL => "https://httpbin.org/delete" #string
// }

func (*Client) Get

func (c *Client) Get[Out any](ctx context.Context, url string, opts ...Option) (Out, error)

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](context.Background(), "https://httpbin.org/get")
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.GetResponse {
//   +URL => "https://httpbin.org/get" #string
// }

Example: read a string body using the same client

resString, err := c.Get[string](context.Background(), "https://httpbin.org/base64/aGVsbG8=")
if err != nil {
	log.Fatal(err)
}
fmt.Println(resString)
// hello

func (*Client) Head

func (c *Client) Head[Out any](ctx context.Context, url string, opts ...Option) (Out, error)

Head issues a HEAD request. A successful HEAD response has an empty body. @group Requests

Example: HEAD request

c := httpclient.New()
body, err := c.Head[string](context.Background(), "https://httpbin.org/get")
if err != nil {
	log.Fatal(err)
}
fmt.Println(len(body))
// 0

func (*Client) Options

func (c *Client) Options[Out any](ctx context.Context, url string, opts ...Option) (Out, error)

Options issues an OPTIONS request and decodes its response. @group Requests

Example: OPTIONS request

c := httpclient.New()
body, err := c.Options[string](context.Background(), "https://httpbin.org/get")
if err != nil {
	log.Fatal(err)
}
fmt.Println(len(body))
// 0

func (*Client) Patch

func (c *Client) Patch[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)

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](context.Background(), "https://httpbin.org/patch", UpdateUser{Name: "Ana"})
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.UpdateUserResponse {
//   +JSON   => #main.UpdateUser {
//     +Name => "Ana" #string
//   }
// }

func (*Client) Post

func (c *Client) Post[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)

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](context.Background(), "https://httpbin.org/post", CreateUser{Name: "Ana"})
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.CreateUserResponse {
//   +JSON   => #main.CreateUser {
//     +Name => "Ana" #string
//   }
// }

func (*Client) Put

func (c *Client) Put[Out any](ctx context.Context, url string, body any, opts ...Option) (Out, error)

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](context.Background(), "https://httpbin.org/put", UpdateUser{Name: "Ana"})
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res)
// #main.UpdateUserResponse {
//   +JSON   => #main.UpdateUser {
//     +Name => "Ana" #string
//   }
// }

func (*Client) Raw

func (c *Client) Raw() *req.Client

Raw returns the underlying req client for chaining raw requests. @group Client

func (*Client) Req

func (c *Client) Req() *req.Client

Req returns the underlying req client for advanced usage. @group Client

func (*Client) Send added in v0.2.0

func (c *Client) Send(ctx context.Context, method, url string, opts ...Option) (*http.Response, error)

Send returns the HTTP response when its headers arrive. Every HTTP status is returned as a response. The caller must close its body. Use Body, JSON, or Form to attach request data. @group Requests

Example: inspect status and headers

c := httpclient.New()
res, err := c.Send(context.Background(), http.MethodGet, "https://httpbin.org/get")
if err != nil {
	return
}
defer res.Body.Close()
fmt.Println(res.StatusCode)
// 200

type ErrorMapperFunc

type ErrorMapperFunc func(*req.Response) error

ErrorMapperFunc customizes error creation for non-2xx responses.

type HTTPError

type HTTPError struct {
	StatusCode int
	Status     string
	Body       []byte
	Header     http.Header
}

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns a short, human-friendly summary of the HTTP error. @group Errors

Example: read the status code from an HTTP error

var transport httpclienttest.Transport
transport.Respond(http.MethodGet, "/orders/42",
	httpclienttest.Response{StatusCode: http.StatusNotFound},
)
client := httpclient.New(
	httpclient.BaseURL("https://api.example.test"),
	httpclient.Transport(&transport),
)
_, err := client.Get[string](context.Background(), "/orders/42")
var httpErr *httpclient.HTTPError
if !errors.As(err, &httpErr) {
	log.Fatalf("expected an HTTP error, got %v", err)
}
fmt.Println(httpErr.StatusCode)
// 404

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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Token abc123" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Auth("Token", "abc123"))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "/uuid")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Basic dXNlcjpwYXNz" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Basic("user", "pass"))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Authorization => "Bearer token" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Bearer("token"))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/get", httpclient.Before(func(r *req.Request) {
	r.EnableDump()
}))
httpclient.Dump(res)
// #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, _ := c.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil, httpclient.Body(Payload{Name: "Ana"}))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/cookies")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.DumpTo(&buf))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.DumpToFile("httpclient.dump"))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.EnableDump())
httpclient.Dump(res)
// #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

Example: map a 500 response

var transport httpclienttest.Transport
transport.Respond(http.MethodGet, "/orders/42",
	httpclienttest.Response{StatusCode: http.StatusInternalServerError},
)
client := httpclient.New(
	httpclient.BaseURL("https://api.example.test"),
	httpclient.Transport(&transport),
	httpclient.ErrorMapper(func(resp *req.Response) error {
		return fmt.Errorf("orders API returned status %d", resp.StatusCode)
	}),
)
_, err := client.Get[string](context.Background(), "/orders/42")
fmt.Println(err)
// orders API returned status 500

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

dir, err := os.MkdirTemp("", "httpclient-upload-")
if err != nil {
	log.Print(err)
	return
}
defer os.RemoveAll(dir)

path := filepath.Join(dir, "report.txt")
if err := os.WriteFile(path, []byte("hello"), 0o600); err != nil {
	log.Print(err)
	return
}

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.File("file", path),
)
if err != nil {
	log.Print(err)
	return
}
httpclient.Dump(res["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

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["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

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileReader("file", "report.txt", strings.NewReader("hello")),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["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

dir, err := os.MkdirTemp("", "httpclient-upload-")
if err != nil {
	log.Print(err)
	return
}
defer os.RemoveAll(dir)

first := filepath.Join(dir, "a.txt")
second := filepath.Join(dir, "b.txt")
if err := os.WriteFile(first, []byte("hello"), 0o600); err != nil {
	log.Print(err)
	return
}
if err := os.WriteFile(second, []byte("world"), 0o600); err != nil {
	log.Print(err)
	return
}

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.Files(map[string]string{
		"fileA": first,
		"fileB": second,
	}),
)
if err != nil {
	log.Print(err)
	return
}
httpclient.Dump(res["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, _ := c.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil, httpclient.Form(map[string]string{
	"name": "alice",
}))
httpclient.Dump(res)
// #map[string]interface {} {
//   form => #map[string]interface {} {
//     name => "alice" #string
//   }
// }
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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Header("X-Trace", "1"))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     Accept => "application/json" #string
//     X-Trace => "1" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.Headers(map[string]string{
	"X-Trace": "1",
	"Accept":  "application/json",
}))
httpclient.Dump(res)
// #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, _ := c.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil, httpclient.JSON(Payload{Name: "Ana"}))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/bytes/1024", httpclient.OutputFile("/tmp/file.bin"))
httpclient.Dump(res)
// 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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/anything/{id}", httpclient.Path("id", 42))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/anything/{org}/users/{id}", httpclient.Paths(map[string]any{
	"org": "goforj",
	"id":  7,
}))
httpclient.Dump(res)
// #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. Use a URL for a proxy you can reach. @group Client Options

Example: configure a proxy

_ = httpclient.New(httpclient.Proxy("http://localhost:8080"))

func ProxyFunc

func ProxyFunc(fn func(*http.Request) (*url.URL, error)) OptionBuilder

ProxyFunc selects a proxy for each request. Pass http.ProxyFromEnvironment to use the HTTP proxy settings in the environment. @group Client Options

Example: configure a proxy function

_ = httpclient.New(httpclient.ProxyFunc(http.ProxyFromEnvironment))

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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/get", httpclient.Queries(map[string]string{
	"q":  "search",
	"ok": "1",
}))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/get", httpclient.Query("q", "search"))
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/redirect/1")
httpclient.Dump(res)
// 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 with jitter between retry attempts. @group Retry

Example: configure backoff

_ = httpclient.New(httpclient.RetryCount(2).RetryBackoff(100*time.Millisecond, 2*time.Second))

func RetryCondition

func RetryCondition(condition req.RetryConditionFunc) OptionBuilder

RetryCondition replaces the default retry condition for a request. Set RetryCount to enable retries. A transport failure can leave the HTTP response absent. @group Retry

Example: retry once after a 503 response

var transport httpclienttest.Transport
transport.Respond(http.MethodGet, "/orders/42",
	httpclienttest.Response{StatusCode: http.StatusServiceUnavailable},
	httpclienttest.Response{Body: []byte("shipped")},
)
client := httpclient.New(
	httpclient.BaseURL("https://api.example.test"),
	httpclient.Transport(&transport),
	httpclient.RetryCount(1),
	httpclient.RetryFixedInterval(0),
	httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
		return resp != nil && resp.Response != nil && resp.StatusCode == http.StatusServiceUnavailable
	}),
)
body, err := client.Get[string](context.Background(), "/orders/42")
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%s after %d attempts\n", body, len(transport.Requests()))
// shipped after 2 attempts

func RetryCount

func RetryCount(count int) OptionBuilder

RetryCount sets the maximum number of retries after the first attempt. It defaults to zero. With retries enabled, the default policy retries transport errors with a fixed 100ms delay. @group Retry

Example: allow up to two retries

_ = httpclient.New(httpclient.RetryCount(2))

func RetryFixedInterval

func RetryFixedInterval(interval time.Duration) OptionBuilder

RetryFixedInterval sets the delay between retry attempts. @group Retry

Example: wait 200ms between retries

_ = httpclient.New(httpclient.RetryCount(2).RetryFixedInterval(200*time.Millisecond))

func RetryHook

func RetryHook(hook req.RetryHookFunc) OptionBuilder

RetryHook registers a callback that runs before each retry attempt. @group Retry

Example: log the error before a retry

_ = httpclient.New(httpclient.RetryCount(2).RetryHook(func(_ *req.Response, err error) {
	fmt.Printf("retrying after %v\n", err)
}))

func RetryInterval

func RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder

RetryInterval sets a function that computes the delay before each retry. @group Retry

Example: increase the delay with each retry

_ = httpclient.New(httpclient.RetryCount(2).RetryInterval(func(_ *req.Response, attempt int) time.Duration {
	return time.Duration(attempt) * 100 * time.Millisecond
}))

func TLSFingerprint

func TLSFingerprint(kind TLSFingerprintKind) OptionBuilder

TLSFingerprint applies a TLS fingerprint preset. @group TLS Fingerprints

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 TLS Fingerprints

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 TLS Fingerprints

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 TLS Fingerprints

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 TLS Fingerprints

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 TLS Fingerprints

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 TLS Fingerprints

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 TLS Fingerprints

Applies to client configuration only. Example: apply Safari TLS fingerprint

_ = httpclient.New(httpclient.TLSFingerprintSafari())

func Timeout

func Timeout(d time.Duration) OptionBuilder

Timeout sets the timeout for each HTTP attempt, including reading the response body. @group Request Control

Use a context deadline to limit the full operation across retries. Example: timeout

// Apply to all requests
c := httpclient.New(httpclient.Timeout(2 * time.Second))
res, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/delay/2")
httpclient.Dump(res)
// map[string]interface {}(nil)

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/delay/2", httpclient.Timeout(2*time.Second))
httpclient.Dump(res)
// 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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid", httpclient.Trace())
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/uuid")
httpclient.Dump(res)
// #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

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	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")
		}
	}),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #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

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	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),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #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

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	httpclient.UploadProgress(),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #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, _ := c.Get[map[string]any](context.Background(), "https://httpbin.org/headers")
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     User-Agent => "my-app/1.0" #string
//   }
// }

// Apply to a single request
res, _ = c.Get[map[string]any](context.Background(), "https://httpbin.org/headers", httpclient.UserAgent("my-app/1.0"))
httpclient.Dump(res)
// #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. @group Debugging

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 (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 (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
)

Directories

Path Synopsis
examples
quick-start command
testing command
Package httpclienttest provides a recording HTTP transport for tests.
Package httpclienttest provides a recording HTTP transport for tests.

Jump to

Keyboard shortcuts

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