httpclient

package module
v0.2.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

Quick Start · Installation · Debugging · API

Quick Start

Use Client.Get to fetch a product and decode its JSON response. The example starts a local HTTP server so you can run it without an external service.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/goforj/httpclient"
)

// Product holds the catalog fields displayed by the client.
type Product struct {
	Name       string `json:"name"`
	PriceCents int    `json:"price_cents"`
}

// main fetches a product from a local catalog fixture.
func main() {
	routes := http.NewServeMux()
	routes.HandleFunc("GET /products/42", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(Product{Name: "Travel mug", PriceCents: 1850}); err != nil {
			log.Print(err)
		}
	})
	server := httptest.NewServer(routes)
	defer server.Close()

	client := httpclient.New()
	product, err := client.Get[Product](context.Background(), server.URL+"/products/42")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s ($%d.%02d)\n", product.Name, product.PriceCents/100, product.PriceCents%100)
	// Output: Travel mug ($18.50)
}

From the repository root, run go run ./examples/quick-start. The program prints Travel mug ($18.50).

Installation

httpclient requires Go 1.27 or newer.

go get github.com/goforj/httpclient

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.

Retries are opt-in. Set RetryCount to retry transport failures, and use RetryCondition to select HTTP statuses to retry. 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.

Status and Headers

Use Client.Send to read status and headers for any HTTP response, including conditional requests that return 304. It returns an *http.Response as soon as the headers arrive. Close the body after reading it.

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

  • HTTP_TRACE=1 enables request/response dumps for all requests.
  • httpclient.EnableDump() enables dump for a single request.
  • httpclient.DumpEachRequest() enables per-request dumps on a client.

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 example programs are compiled by the test suite. The quick start also runs against its local fixture and checks the displayed output.

See Migrate from Httpx for the import change and supported legacy versions.

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 · Trace · TraceAll
Download Options OutputFile
Errors HTTPError.Error
Other OptionBuilder.DumpToFile · dumpFileWriter.Write · requestContext.Value
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 · Delete · Do · Get · Head · Options · Patch · Post · Put
Retry RetryBackoff · RetryCondition · RetryCount · RetryFixedInterval · RetryHook · RetryInterval
Retry (Client) Retry
Upload Options File · FileBytes · FileReader · Files · UploadCallback · UploadCallbackWithInterval · UploadProgress
Advanced TLSFingerprint · TLSFingerprintAndroid · TLSFingerprintChrome · TLSFingerprintEdge · TLSFingerprintFirefox · TLSFingerprintIOS · TLSFingerprintRandomized · TLSFingerprintSafari

Auth

Auth

Auth sets the Authorization header using a scheme and token.

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

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

Basic

Basic sets HTTP basic authentication headers.

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

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

Bearer

Bearer sets the Authorization header with a bearer token.

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

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

Browser Profiles

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, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/headers")
httpclient.Dump(res) // dumps map[string]any
// #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 client with opinionated defaults and optional overrides.

var buf bytes.Buffer
_ = httpclient.New(httpclient.
	BaseURL("https://httpbin.org").
	Timeout(5*time.Second).
	Header("X-Trace", "1").
	Header("Accept", "application/json").
	Transport(http.RoundTripper(http.DefaultTransport)).
	Middleware(func(_ *req.Client, r *req.Request) error {
		r.SetHeader("X-Middleware", "1")
		return nil
	}).
	ErrorMapper(func(resp *req.Response) error {
		return fmt.Errorf("status %d", resp.StatusCode)
	}).
	DumpAll().
	DumpEachRequest().
	DumpEachRequestTo(&buf).
	Retry(func(rc *req.Client) {
		rc.SetCommonRetryCount(2)
	}).
	RetryCount(2).
	RetryFixedInterval(200*time.Millisecond).
	RetryBackoff(100*time.Millisecond, 2*time.Second).
	RetryInterval(func(_ *req.Response, attempt int) time.Duration {
		return time.Duration(attempt) * 100 * time.Millisecond
	}).
	RetryCondition(func(resp *req.Response, _ error) bool {
		return resp != nil && resp.StatusCode == 503
	}).
	RetryHook(func(_ *req.Response, _ error) {}),
)

Client Options

BaseURL

BaseURL sets a base URL on the client.

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

ErrorMapper

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

c := httpclient.New(httpclient.ErrorMapper(func(resp *req.Response) error {
	return fmt.Errorf("status %d", resp.StatusCode)
}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/500")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

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

Proxy

Proxy sets a proxy URL for the client.

c := httpclient.New(httpclient.Proxy("http://localhost:8080"))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/get")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

ProxyFunc

ProxyFunc sets a proxy function for the client.

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

Redirect

Redirect sets the redirect policy for the client.

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

Transport

Transport wraps the underlying transport with a custom RoundTripper.

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

Debugging

Dump

Dump prints values using the bundled godump formatter.

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

DumpEachRequest

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

c := httpclient.New(httpclient.DumpEachRequest())
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #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, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #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, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.DumpTo(&buf))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

DumpToFile

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

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

EnableDump

EnableDump enables req's request-level dump output.

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

Trace

Trace enables req's request-level trace output.

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

TraceAll

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

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

Download Options

OutputFile

OutputFile streams the response body to a file path.

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

Errors

HTTPError.Error

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

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

c := httpclient.New()
res, err := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/404")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
var httpErr *httpclient.HTTPError
if errors.As(err, &httpErr) {
	_ = httpErr.StatusCode
}

Other

OptionBuilder.DumpToFile

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

dumpFileWriter.Write

Write closes the file after each chunk because a caller may read a streamed response later.

requestContext.Value

Value gives the caller context priority over values installed during request setup.

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

Form

Form sets form data for the request.

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

Header

Header sets a header on a request or client.

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

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

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

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

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

Path

Path sets a path parameter by name.

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

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

Paths

Paths sets multiple path parameters from a map.

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

Queries

Queries sets query parameters from a map.

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

Query

Query adds query parameters as key/value pairs.

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

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

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

Request Control

Before

Before runs a hook before the request is sent.

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

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

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/delay/2", httpclient.Timeout(2*time.Second))
httpclient.Dump(res) // dumps map[string]any
// 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 {
	return
}
fmt.Println(res.URL)
// https://httpbin.org/delete

Client.Get

Get issues a GET request and decodes its response.

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

c := httpclient.New()
res, err := c.Get[GetResponse](context.Background(), "https://httpbin.org/get")
fmt.Println(err == nil, res.URL)
// true https://httpbin.org/get

Client.Head

Head issues a HEAD request and decodes its response using the established response contract.

c := httpclient.New()
_, err := c.Head[[]byte](context.Background(), "https://httpbin.org/get")
fmt.Println(err == nil)
// true

Client.Options

Options issues an OPTIONS request and decodes its response.

c := httpclient.New()
_, err := c.Options[[]byte](context.Background(), "https://httpbin.org/get")
fmt.Println(err == nil)
// true

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 {
	return
}
fmt.Println(res.JSON.Name)
// Ana

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 {
	return
}
fmt.Println(res.JSON.Name)
// Ana

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 {
	return
}
fmt.Println(res.JSON.Name)
// Ana

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

Delete

Delete issues a DELETE request using the provided client. Client.Delete offers the same operation as a method.

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

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

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) // dumps map[string]any
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }
println(rawResp.StatusCode)

Get

Get issues a GET request using the provided client. Client.Get offers the same operation as a method.

Example: bind to a struct

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

c := httpclient.New()
res, _ := httpclient.Get[GetResponse](context.Background(), c, "https://httpbin.org/get")
httpclient.Dump(res)
// #GetResponse {
//   URL => "https://httpbin.org/get" #string
// }

Example: bind to a string body

resString, _ := httpclient.Get[string](context.Background(), c, "https://httpbin.org/uuid")
println(resString) // dumps string
// {
//   "uuid": "becbda6d-9950-4966-ae23-0369617ba065"
// }

Head

Head issues a HEAD request using the provided client. It remains available for compatibility; new code can use Client.Head.

c := httpclient.New()
_, err := httpclient.Head[string](context.Background(), c, "https://httpbin.org/get")
if err != nil {
	return
}

Options

Options issues an OPTIONS request using the provided client. It remains available for compatibility; new code can use Client.Options.

c := httpclient.New()
_, err := httpclient.Options[string](context.Background(), c, "https://httpbin.org/get")
if err != nil {
	return
}

Patch

Patch issues a PATCH request using the provided client. Client.Patch offers the same operation as a method.

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

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

Post

Post issues a POST request using the provided client. Client.Post offers the same operation as a method.

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

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

Put

Put issues a PUT request using the provided client. Client.Put offers the same operation as a method.

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

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

Retry

RetryBackoff

RetryBackoff sets a capped exponential backoff retry interval for a request. Overrides the req default interval (fixed 100ms) with jittered backoff.

// Apply to all requests
c := httpclient.New(httpclient.RetryBackoff(100*time.Millisecond, 2*time.Second))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryBackoff(100*time.Millisecond, 2*time.Second))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

RetryCondition

RetryCondition sets the retry condition for a request. Overrides the default behavior (retry only when a request error occurs).

// Apply to all requests
c := httpclient.New(httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
	return resp != nil && resp.StatusCode == 503
}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/503")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/503", httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
	return resp != nil && resp.StatusCode == 503
}))
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

RetryCount

RetryCount enables retry for a request and sets the maximum retry count. Default behavior from req: retries are disabled (count = 0). When enabled, retries happen only on request errors unless RetryCondition is set, and the default interval is a fixed 100ms between attempts.

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

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryCount(2))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

RetryFixedInterval

RetryFixedInterval sets a fixed retry interval for a request. Overrides the req default interval (fixed 100ms).

// Apply to all requests
c := httpclient.New(httpclient.RetryFixedInterval(200 * time.Millisecond))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryFixedInterval(200*time.Millisecond))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

RetryHook

RetryHook registers a retry hook for a request. Runs before each retry attempt; no hooks are configured by default.

// Apply to all requests
c := httpclient.New(httpclient.RetryHook(func(_ *req.Response, _ error) {}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryHook(func(_ *req.Response, _ error) {}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

RetryInterval

RetryInterval sets a custom retry interval function for a request. Overrides the req default interval (fixed 100ms).

// Apply to all requests
c := httpclient.New(httpclient.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
	return time.Duration(attempt) * 100 * time.Millisecond
}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
	return time.Duration(attempt) * 100 * time.Millisecond
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

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.

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil, httpclient.File("file", "/tmp/report.txt"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "hello" #string
//   }
// }

FileBytes

FileBytes attaches a file from bytes as multipart form data.

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

FileReader

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

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

Files

Files attaches multiple files from disk as multipart form data.

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil, httpclient.Files(map[string]string{
	"fileA": "/tmp/a.txt",
	"fileB": "/tmp/b.txt",
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     fileA => "hello" #string
//     fileB => "world" #string
//   }
// }

UploadCallback

UploadCallback registers a callback for upload progress.

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil,
	httpclient.File("file", "/tmp/report.bin"),
	httpclient.UploadCallback(func(info req.UploadInfo) {
		percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
		fmt.Printf("\rprogress: %.1f%%", percent)
		if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
			fmt.Print("\n")
		}
	}),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "<file>" #string
//   }
// }

UploadCallbackWithInterval

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

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil,
	httpclient.File("file", "/tmp/report.bin"),
	httpclient.UploadCallbackWithInterval(func(info req.UploadInfo) {
		percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
		fmt.Printf("\rprogress: %.1f%% (%.0f bytes)", percent, float64(info.UploadedSize))
		if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
			fmt.Print("\n")
		}
	}, 200*time.Millisecond),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "<file>" #string
//   }
// }

UploadProgress

UploadProgress enables a default progress spinner and bar for uploads.

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil,
	httpclient.File("file", "/tmp/report.bin"),
	httpclient.UploadProgress(),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "<file>" #string
//   }
// }

Advanced

TLSFingerprint

TLSFingerprint applies a TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprint(httpclient.TLSFingerprintChromeKind))

TLSFingerprintAndroid

TLSFingerprintAndroid applies the Android TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprintAndroid())

TLSFingerprintChrome

TLSFingerprintChrome applies the Chrome TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprintChrome())

TLSFingerprintEdge

TLSFingerprintEdge applies the Edge TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprintEdge())

TLSFingerprintFirefox

TLSFingerprintFirefox applies the Firefox TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprintFirefox())

TLSFingerprintIOS

TLSFingerprintIOS applies the iOS TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprintIOS())

TLSFingerprintRandomized

TLSFingerprintRandomized applies a randomized TLS fingerprint preset.

_ = httpclient.New(httpclient.TLSFingerprintRandomized())

TLSFingerprintSafari

TLSFingerprintSafari applies the Safari TLS fingerprint preset.

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

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 Delete

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

Delete issues a DELETE request using the provided client. Client.Delete offers the same operation as a method. @group Requests

Example: typed DELETE

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

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

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) // dumps map[string]any
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }
println(rawResp.StatusCode)

func Dump

func Dump(values ...any)

Dump prints values using the bundled godump formatter. @group Debugging

Example: dump a response

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

func Get

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

Get issues a GET request using the provided client. Client.Get offers the same operation as a method. @group Requests

Example: bind to a struct

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

c := httpclient.New()
res, _ := httpclient.Get[GetResponse](context.Background(), c, "https://httpbin.org/get")
httpclient.Dump(res)
// #GetResponse {
//   URL => "https://httpbin.org/get" #string
// }

Example: bind to a string body

resString, _ := httpclient.Get[string](context.Background(), c, "https://httpbin.org/uuid")
println(resString) // dumps string
// {
//   "uuid": "becbda6d-9950-4966-ae23-0369617ba065"
// }
func Head[T any](ctx context.Context, client *Client, url string, opts ...Option) (T, error)

Head issues a HEAD request using the provided client. It remains available for compatibility; new code can use Client.Head. @group Requests

Example: HEAD request

c := httpclient.New()
_, err := httpclient.Head[string](context.Background(), c, "https://httpbin.org/get")
if err != nil {
	return
}

func Options

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

Options issues an OPTIONS request using the provided client. It remains available for compatibility; new code can use Client.Options. @group Requests

Example: OPTIONS request

c := httpclient.New()
_, err := httpclient.Options[string](context.Background(), c, "https://httpbin.org/get")
if err != nil {
	return
}

func Patch

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

Patch issues a PATCH request using the provided client. Client.Patch offers the same operation as a method. @group Requests

Example: typed PATCH

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

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

func Post

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

Post issues a POST request using the provided client. Client.Post offers the same operation as a method. @group Requests

Example: typed POST

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

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

func Put

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

Put issues a PUT request using the provided client. Client.Put offers the same operation as a method. @group Requests

Example: typed PUT

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

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

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps a req client with typed helpers and defaults. @group Client

func Default

func Default() *Client

Default returns the shared default client. @group Client

func New

func New(opts ...Option) *Client

New creates a client with opinionated defaults and optional overrides. @group Client

Example: configure all client options

var buf bytes.Buffer
_ = httpclient.New(httpclient.
	BaseURL("https://httpbin.org").
	Timeout(5*time.Second).
	Header("X-Trace", "1").
	Header("Accept", "application/json").
	Transport(http.RoundTripper(http.DefaultTransport)).
	Middleware(func(_ *req.Client, r *req.Request) error {
		r.SetHeader("X-Middleware", "1")
		return nil
	}).
	ErrorMapper(func(resp *req.Response) error {
		return fmt.Errorf("status %d", resp.StatusCode)
	}).
	DumpAll().
	DumpEachRequest().
	DumpEachRequestTo(&buf).
	Retry(func(rc *req.Client) {
		rc.SetCommonRetryCount(2)
	}).
	RetryCount(2).
	RetryFixedInterval(200*time.Millisecond).
	RetryBackoff(100*time.Millisecond, 2*time.Second).
	RetryInterval(func(_ *req.Response, attempt int) time.Duration {
		return time.Duration(attempt) * 100 * time.Millisecond
	}).
	RetryCondition(func(resp *req.Response, _ error) bool {
		return resp != nil && resp.StatusCode == 503
	}).
	RetryHook(func(_ *req.Response, _ error) {}),
)

func (*Client) Delete

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 {
	return
}
fmt.Println(res.URL)
// https://httpbin.org/delete

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")
fmt.Println(err == nil, res.URL)
// true https://httpbin.org/get

func (*Client) Head

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

Head issues a HEAD request and decodes its response using the established response contract. @group Requests

Example: client HEAD request

c := httpclient.New()
_, err := c.Head[[]byte](context.Background(), "https://httpbin.org/get")
fmt.Println(err == nil)
// true

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: client OPTIONS request

c := httpclient.New()
_, err := c.Options[[]byte](context.Background(), "https://httpbin.org/get")
fmt.Println(err == nil)
// true

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 {
	return
}
fmt.Println(res.JSON.Name)
// Ana

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 {
	return
}
fmt.Println(res.JSON.Name)
// Ana

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 {
	return
}
fmt.Println(res.JSON.Name)
// Ana

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: check for HTTP errors

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

c := httpclient.New()
res, err := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/404")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)
var httpErr *httpclient.HTTPError
if errors.As(err, &httpErr) {
	_ = httpErr.StatusCode
}

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option applies configuration to a client or request.

type OptionBuilder

type OptionBuilder struct {
	// contains filtered or unexported fields
}

OptionBuilder chains request and client options. @group Options

Example: chain options

opt := httpclient.Header("X-Trace", "1").Query("q", "go")
_ = opt

func AsChrome

func AsChrome() OptionBuilder

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

Applies to client configuration only. Example: use a Chrome profile

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

func AsFirefox

func AsFirefox() OptionBuilder

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

Applies to client configuration only. Example: use a Firefox profile

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

func AsMobile

func AsMobile() OptionBuilder

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

Applies to client configuration only. Example: use a mobile profile

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

func AsSafari

func AsSafari() OptionBuilder

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

Applies to client configuration only. Example: use a Safari profile

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

func Auth

func Auth(scheme, token string) OptionBuilder

Auth sets the Authorization header using a scheme and token. @group Auth Applies to both client defaults and request-time overrides.

Example: custom auth scheme

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

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

func BaseURL

func BaseURL(url string) OptionBuilder

BaseURL sets a base URL on the client. @group Client Options

Applies to client configuration only. Example: client base URL

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

func Basic

func Basic(user, pass string) OptionBuilder

Basic sets HTTP basic authentication headers. @group Auth Applies to both client defaults and request-time overrides.

Example: basic auth

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

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

func Bearer

func Bearer(token string) OptionBuilder

Bearer sets the Authorization header with a bearer token. @group Auth Applies to both client defaults and request-time overrides.

Example: bearer auth

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

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

func Before

func Before(fn func(*req.Request)) OptionBuilder

Before runs a hook before the request is sent. @group Request Control

Applies to individual requests only. Example: mutate req.Request

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

func Body

func Body(value any) OptionBuilder

Body sets the request body and infers JSON for structs and maps. @group Request Composition

Applies to individual requests only. Example: send JSON body with inference

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

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

func CookieJar

func CookieJar(jar http.CookieJar) OptionBuilder

CookieJar sets the cookie jar for the client. @group Client Options

Applies to client configuration only. Example: set cookie jar and seed cookies

jar, _ := cookiejar.New(nil)
u, _ := url.Parse("https://httpbin.org")
jar.SetCookies(u, []*http.Cookie{
	{Name: "session", Value: "abc123"},
})
c := httpclient.New(httpclient.CookieJar(jar))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/cookies")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   cookies => #map[string]interface {} {
//     session => "abc123" #string
//   }
// }

func DumpAll

func DumpAll() OptionBuilder

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

Applies to the client configuration only. Example: dump every request and response

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

func DumpEachRequest

func DumpEachRequest() OptionBuilder

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

Applies to the client configuration only. Example: dump each request as it is sent

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

func DumpEachRequestTo

func DumpEachRequestTo(output io.Writer) OptionBuilder

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

Applies to the client configuration only. Example: dump each request to a buffer

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

func DumpTo

func DumpTo(output io.Writer) OptionBuilder

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

Applies to individual requests only. Example: dump to a buffer

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

func DumpToFile

func DumpToFile(filename string) OptionBuilder

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

Applies to individual requests only. Example: dump to a file

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

func EnableDump

func EnableDump() OptionBuilder

EnableDump enables req's request-level dump output. @group Debugging

Applies to individual requests only. Example: dump a single request

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

func ErrorMapper

func ErrorMapper(fn ErrorMapperFunc) OptionBuilder

ErrorMapper sets a custom error mapper for non-2xx responses. @group Client Options

Applies only to the client configuration. Example: map error responses

c := httpclient.New(httpclient.ErrorMapper(func(resp *req.Response) error {
	return fmt.Errorf("status %d", resp.StatusCode)
}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/500")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

func File

func File(paramName, filePath string) OptionBuilder

File attaches a file from disk as multipart form data. @group Upload Options

Applies to individual requests only. Example: upload a file

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil, httpclient.File("file", "/tmp/report.txt"))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "hello" #string
//   }
// }

func FileBytes

func FileBytes(paramName, filename string, content []byte) OptionBuilder

FileBytes attaches a file from bytes as multipart form data. @group Upload Options

Applies to individual requests only. Example: upload bytes as a file

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

func FileReader

func FileReader(paramName, filename string, reader io.Reader) OptionBuilder

FileReader attaches a file from a reader as multipart form data. @group Upload Options

Applies to individual requests only. Example: upload from reader

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

func Files

func Files(files map[string]string) OptionBuilder

Files attaches multiple files from disk as multipart form data. @group Upload Options

Applies to individual requests only. Example: upload multiple files

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil, httpclient.Files(map[string]string{
	"fileA": "/tmp/a.txt",
	"fileB": "/tmp/b.txt",
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     fileA => "hello" #string
//     fileB => "world" #string
//   }
// }

func Form

func Form(values map[string]string) OptionBuilder

Form sets form data for the request. @group Request Composition

Applies to individual requests only. Example: submit a form

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

Header sets a header on a request or client. @group Request Composition

Applies to both client defaults and request-time headers. Example: apply a header

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

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

func Headers

func Headers(values map[string]string) OptionBuilder

Headers sets multiple headers on a request or client. @group Request Composition

Applies to both client defaults and request-time headers. Example: apply headers

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

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

func JSON

func JSON(value any) OptionBuilder

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

Applies to individual requests only. Example: force JSON body

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

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

func Middleware

func Middleware(mw ...req.RequestMiddleware) OptionBuilder

Middleware adds request middleware to the client. @group Client Options

Applies only to the client configuration. Example: add request middleware

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

func OutputFile

func OutputFile(path string) OptionBuilder

OutputFile streams the response body to a file path. @group Download Options

Applies to individual requests only. Example: download to file

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

func Path

func Path(key string, value any) OptionBuilder

Path sets a path parameter by name. @group Request Composition

Applies to individual requests only. Example: path parameter

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

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

func Paths

func Paths(values map[string]any) OptionBuilder

Paths sets multiple path parameters from a map. @group Request Composition

Applies to individual requests only. Example: path parameters

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

func Proxy

func Proxy(proxyURL string) OptionBuilder

Proxy sets a proxy URL for the client. @group Client Options

Applies to client configuration only. Example: set proxy URL

c := httpclient.New(httpclient.Proxy("http://localhost:8080"))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/get")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

func ProxyFunc

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

ProxyFunc sets a proxy function for the client. @group Client Options

Applies to client configuration only. Example: set proxy function

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

func Queries

func Queries(values map[string]string) OptionBuilder

Queries sets query parameters from a map. @group Request Composition

Applies to individual requests only. Example: add query params

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

func Query

func Query(kv ...string) OptionBuilder

Query adds query parameters as key/value pairs. @group Request Composition

Applies to individual requests only. Example: add query params

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

func Redirect

func Redirect(policies ...req.RedirectPolicy) OptionBuilder

Redirect sets the redirect policy for the client. @group Client Options

Applies to client configuration only. Example: disable redirects

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

func Retry

func Retry(fn func(*req.Client)) OptionBuilder

Retry applies a custom retry configuration to the client. Defaults remain in effect unless the callback modifies them. @group Retry (Client)

Applies only to client configuration. Example: configure client retry

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

func RetryBackoff

func RetryBackoff(min, max time.Duration) OptionBuilder

RetryBackoff sets a capped exponential backoff retry interval for a request. Overrides the req default interval (fixed 100ms) with jittered backoff. @group Retry

Applies to both client defaults and individual requests. Example: retry backoff

// Apply to all requests
c := httpclient.New(httpclient.RetryBackoff(100*time.Millisecond, 2*time.Second))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryBackoff(100*time.Millisecond, 2*time.Second))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

func RetryCondition

func RetryCondition(condition req.RetryConditionFunc) OptionBuilder

RetryCondition sets the retry condition for a request. Overrides the default behavior (retry only when a request error occurs). @group Retry

Applies to both client defaults and individual requests. Example: retry on 503

// Apply to all requests
c := httpclient.New(httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
	return resp != nil && resp.StatusCode == 503
}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/503")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/status/503", httpclient.RetryCondition(func(resp *req.Response, _ error) bool {
	return resp != nil && resp.StatusCode == 503
}))
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

func RetryCount

func RetryCount(count int) OptionBuilder

RetryCount enables retry for a request and sets the maximum retry count. Default behavior from req: retries are disabled (count = 0). When enabled, retries happen only on request errors unless RetryCondition is set, and the default interval is a fixed 100ms between attempts. @group Retry

Applies to both client defaults and individual requests. Example: retry count

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

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryCount(2))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

func RetryFixedInterval

func RetryFixedInterval(interval time.Duration) OptionBuilder

RetryFixedInterval sets a fixed retry interval for a request. Overrides the req default interval (fixed 100ms). @group Retry

Applies to both client defaults and individual requests. Example: retry interval

// Apply to all requests
c := httpclient.New(httpclient.RetryFixedInterval(200 * time.Millisecond))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryFixedInterval(200*time.Millisecond))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

func RetryHook

func RetryHook(hook req.RetryHookFunc) OptionBuilder

RetryHook registers a retry hook for a request. Runs before each retry attempt; no hooks are configured by default. @group Retry

Applies to both client defaults and individual requests. Example: hook on retry

// Apply to all requests
c := httpclient.New(httpclient.RetryHook(func(_ *req.Response, _ error) {}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryHook(func(_ *req.Response, _ error) {}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

func RetryInterval

func RetryInterval(fn req.GetRetryIntervalFunc) OptionBuilder

RetryInterval sets a custom retry interval function for a request. Overrides the req default interval (fixed 100ms). @group Retry

Applies to both client defaults and individual requests. Example: custom retry interval

// Apply to all requests
c := httpclient.New(httpclient.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
	return time.Duration(attempt) * 100 * time.Millisecond
}))
res, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid")
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

// Apply to a single request
res, _ = httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/uuid", httpclient.RetryInterval(func(_ *req.Response, attempt int) time.Duration {
	return time.Duration(attempt) * 100 * time.Millisecond
}))
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   uuid => "<uuid>" #string
// }

func TLSFingerprint

func TLSFingerprint(kind TLSFingerprintKind) OptionBuilder

TLSFingerprint applies a TLS fingerprint preset. @group Advanced

Applies to client configuration only. Example: apply a TLS fingerprint preset

_ = httpclient.New(httpclient.TLSFingerprint(httpclient.TLSFingerprintChromeKind))

func TLSFingerprintAndroid

func TLSFingerprintAndroid() OptionBuilder

TLSFingerprintAndroid applies the Android TLS fingerprint preset. @group Advanced

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

_ = httpclient.New(httpclient.TLSFingerprintAndroid())

func TLSFingerprintChrome

func TLSFingerprintChrome() OptionBuilder

TLSFingerprintChrome applies the Chrome TLS fingerprint preset. @group Advanced

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

_ = httpclient.New(httpclient.TLSFingerprintChrome())

func TLSFingerprintEdge

func TLSFingerprintEdge() OptionBuilder

TLSFingerprintEdge applies the Edge TLS fingerprint preset. @group Advanced

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

_ = httpclient.New(httpclient.TLSFingerprintEdge())

func TLSFingerprintFirefox

func TLSFingerprintFirefox() OptionBuilder

TLSFingerprintFirefox applies the Firefox TLS fingerprint preset. @group Advanced

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

_ = httpclient.New(httpclient.TLSFingerprintFirefox())

func TLSFingerprintIOS

func TLSFingerprintIOS() OptionBuilder

TLSFingerprintIOS applies the iOS TLS fingerprint preset. @group Advanced

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

_ = httpclient.New(httpclient.TLSFingerprintIOS())

func TLSFingerprintRandomized

func TLSFingerprintRandomized() OptionBuilder

TLSFingerprintRandomized applies a randomized TLS fingerprint preset. @group Advanced

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

_ = httpclient.New(httpclient.TLSFingerprintRandomized())

func TLSFingerprintSafari

func TLSFingerprintSafari() OptionBuilder

TLSFingerprintSafari applies the Safari TLS fingerprint preset. @group Advanced

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

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

func Timeout

func Timeout(d time.Duration) OptionBuilder

Timeout sets 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, _ := httpclient.Get[map[string]any](context.Background(), c, "https://httpbin.org/delay/2")
httpclient.Dump(res) // dumps map[string]any
// map[string]interface {}(nil)

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

func Trace

func Trace() OptionBuilder

Trace enables req's request-level trace output. @group Debugging

Applies to individual requests only. Example: trace a single request

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

func TraceAll

func TraceAll() OptionBuilder

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

Applies to the client configuration only. Example: trace all requests

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

func Transport

func Transport(rt http.RoundTripper) OptionBuilder

Transport wraps the underlying transport with a custom RoundTripper. @group Client Options

Applies to client configuration only. Example: wrap transport

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

func UploadCallback

func UploadCallback(callback req.UploadCallback) OptionBuilder

UploadCallback registers a callback for upload progress. @group Upload Options

Applies to individual requests only. Example: track upload progress

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil,
	httpclient.File("file", "/tmp/report.bin"),
	httpclient.UploadCallback(func(info req.UploadInfo) {
		percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
		fmt.Printf("\rprogress: %.1f%%", percent)
		if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
			fmt.Print("\n")
		}
	}),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "<file>" #string
//   }
// }

func UploadCallbackWithInterval

func UploadCallbackWithInterval(callback req.UploadCallback, minInterval time.Duration) OptionBuilder

UploadCallbackWithInterval registers a callback for upload progress with a minimum interval. @group Upload Options

Applies to individual requests only. Example: throttle upload progress updates

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil,
	httpclient.File("file", "/tmp/report.bin"),
	httpclient.UploadCallbackWithInterval(func(info req.UploadInfo) {
		percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
		fmt.Printf("\rprogress: %.1f%% (%.0f bytes)", percent, float64(info.UploadedSize))
		if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
			fmt.Print("\n")
		}
	}, 200*time.Millisecond),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "<file>" #string
//   }
// }

func UploadProgress

func UploadProgress() OptionBuilder

UploadProgress enables a default progress spinner and bar for uploads. @group Upload Options Applies to individual requests only.

Example: upload with automatic progress

c := httpclient.New()
res, _ := httpclient.Post[any, map[string]any](context.Background(), c, "https://httpbin.org/post", nil,
	httpclient.File("file", "/tmp/report.bin"),
	httpclient.UploadProgress(),
)
httpclient.Dump(res) // dumps map[string]any
// #map[string]interface {} {
//   files => #map[string]interface {} {
//     file => "<file>" #string
//   }
// }

func UserAgent

func UserAgent(value string) OptionBuilder

UserAgent sets the User-Agent header on a request or client. @group Request Composition

Applies to both client defaults and request-time headers. Example: set a User-Agent

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

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

func (OptionBuilder) AsChrome

func (b OptionBuilder) AsChrome() OptionBuilder

func (OptionBuilder) AsFirefox

func (b OptionBuilder) AsFirefox() OptionBuilder

func (OptionBuilder) AsMobile

func (b OptionBuilder) AsMobile() OptionBuilder

func (OptionBuilder) AsSafari

func (b OptionBuilder) AsSafari() OptionBuilder

func (OptionBuilder) Auth

func (b OptionBuilder) Auth(scheme, token string) OptionBuilder

func (OptionBuilder) BaseURL

func (b OptionBuilder) BaseURL(url string) OptionBuilder

func (OptionBuilder) Basic

func (b OptionBuilder) Basic(user, pass string) OptionBuilder

func (OptionBuilder) Bearer

func (b OptionBuilder) Bearer(token string) OptionBuilder

func (OptionBuilder) Before

func (b OptionBuilder) Before(fn func(*req.Request)) OptionBuilder

func (OptionBuilder) Body

func (b OptionBuilder) Body(value any) OptionBuilder

func (OptionBuilder) CookieJar

func (b OptionBuilder) CookieJar(jar http.CookieJar) OptionBuilder

func (OptionBuilder) DumpAll

func (b OptionBuilder) DumpAll() OptionBuilder

func (OptionBuilder) DumpEachRequest

func (b OptionBuilder) DumpEachRequest() OptionBuilder

func (OptionBuilder) DumpEachRequestTo

func (b OptionBuilder) DumpEachRequestTo(output io.Writer) OptionBuilder

func (OptionBuilder) DumpTo

func (b OptionBuilder) DumpTo(output io.Writer) OptionBuilder

func (OptionBuilder) DumpToFile

func (b OptionBuilder) DumpToFile(filename string) OptionBuilder

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

func (OptionBuilder) EnableDump

func (b OptionBuilder) EnableDump() OptionBuilder

func (OptionBuilder) ErrorMapper

func (b OptionBuilder) ErrorMapper(fn ErrorMapperFunc) OptionBuilder

func (OptionBuilder) File

func (b OptionBuilder) File(paramName, filePath string) OptionBuilder

func (OptionBuilder) FileBytes

func (b OptionBuilder) FileBytes(paramName, filename string, content []byte) OptionBuilder

func (OptionBuilder) FileReader

func (b OptionBuilder) FileReader(paramName, filename string, reader io.Reader) OptionBuilder

func (OptionBuilder) Files

func (b OptionBuilder) Files(files map[string]string) OptionBuilder

func (OptionBuilder) Form

func (b OptionBuilder) Form(values map[string]string) OptionBuilder

func (OptionBuilder) Header

func (b OptionBuilder) Header(key, value string) OptionBuilder

func (OptionBuilder) Headers

func (b OptionBuilder) Headers(values map[string]string) OptionBuilder

func (OptionBuilder) JSON

func (b OptionBuilder) JSON(value any) OptionBuilder

func (OptionBuilder) Middleware

func (b OptionBuilder) Middleware(mw ...req.RequestMiddleware) OptionBuilder

func (OptionBuilder) OutputFile

func (b OptionBuilder) OutputFile(path string) OptionBuilder

func (OptionBuilder) Path

func (b OptionBuilder) Path(key string, value any) OptionBuilder

func (OptionBuilder) Paths

func (b OptionBuilder) Paths(values map[string]any) OptionBuilder

func (OptionBuilder) Proxy

func (b OptionBuilder) Proxy(proxyURL string) OptionBuilder

func (OptionBuilder) ProxyFunc

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

func (OptionBuilder) Queries

func (b OptionBuilder) Queries(values map[string]string) OptionBuilder

func (OptionBuilder) Query

func (b OptionBuilder) Query(kv ...string) OptionBuilder

func (OptionBuilder) Redirect

func (b OptionBuilder) Redirect(policies ...req.RedirectPolicy) OptionBuilder

func (OptionBuilder) Retry

func (b OptionBuilder) Retry(fn func(*req.Client)) OptionBuilder

func (OptionBuilder) RetryBackoff

func (b OptionBuilder) RetryBackoff(min, max time.Duration) OptionBuilder

func (OptionBuilder) RetryCondition

func (b OptionBuilder) RetryCondition(condition req.RetryConditionFunc) OptionBuilder

func (OptionBuilder) RetryCount

func (b OptionBuilder) RetryCount(count int) OptionBuilder

func (OptionBuilder) RetryFixedInterval

func (b OptionBuilder) RetryFixedInterval(interval time.Duration) OptionBuilder

func (OptionBuilder) RetryHook

func (b OptionBuilder) RetryHook(hook req.RetryHookFunc) OptionBuilder

func (OptionBuilder) RetryInterval

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