Skip to content
Proyek

Tentang

HTTP client for Go with typed responses, retries, and authentication.

Keamanan dan privasi

Cara angka ini diukur

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
-1
dalam 15 hari
-1
dalam 1 bulan
-1

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

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 License: MIT Go Test Security Go version Latest version Published GitHub release count Coverage Tests

Installation · Quick Start · Debugging · API

Installation

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

go get github.com/goforj/httpclient

Quick Start

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

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/goforj/httpclient"
)

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

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

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

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

Status and Headers

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

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

Context and Retries

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

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

Testing

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

package main

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

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

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

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

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

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

Debugging and Tracing

Timings

Use Trace() for one request or TraceAll() for a client. When a call is slow, compare DNS and TLS timings with the wait for the first response byte after the connection is ready. This example reads TraceInfo() from the underlying req response. Go example

go run ./examples/traceall/main.go
# DNS 67ms, TLS 49ms, first byte 34ms, total 186ms

Request and Response Dumps

For an unexpected status or body, use DumpTo(os.Stdout) on the request to see what went over HTTP. This example shows one run over HTTP/2.

client := httpclient.New()
_, err := client.Get[string](context.Background(),
	"https://httpbin.org/base64/aGVsbG8=",
	httpclient.DumpTo(os.Stdout),
)
if err != nil {
	log.Fatal(err)
}
// :authority: httpbin.org
// :method: GET
// :path: /base64/aGVsbG8=
// :scheme: https
// user-agent: httpclient (https://github.com/goforj/httpclient)
// accept-encoding: gzip
//
// :status: 200
// access-control-allow-credentials: true
// access-control-allow-origin: *
// access-control-expose-headers: Retry-After, RateLimit, RateLimit-Policy, WWW-Authenticate
// content-length: 5
// content-type: text/plain; charset=utf-8
// x-content-type-options: nosniff
// date: Thu, 03 Dec 2026 09:18:35 GMT
//
// hello

Use httpclient.New(httpclient.DumpAll()) to print every exchange on one client. Set HTTP_TRACE to dump exchanges from all newly created clients in a run. Compare the response with curl to see what the endpoint returns outside your app.

HTTP_TRACE=1 go run ./examples/traceall/main.go
curl -siS 'https://httpbin.org/base64/aGVsbG8='

Unset HTTP_TRACE to disable those dumps. Any set value enables them, and the headers and bodies may contain credentials.

API Index

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

Auth

Auth

Auth sets the Authorization header using a scheme and token.

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

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

Basic

Basic sets HTTP basic authentication headers.

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

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

Bearer

Bearer sets the Authorization header with a bearer token.

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

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

Browser Profiles

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

AsChrome

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

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

AsFirefox

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

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

AsMobile

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

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

AsSafari

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

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

Client

Client.Raw

Raw returns the underlying req client for chaining raw requests.

Client.Req

Req returns the underlying req client for advanced usage.

Default

Default returns the shared default client.

New

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

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

Client Options

BaseURL

BaseURL sets a base URL on the client.

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

CookieJar

CookieJar sets the cookie jar for the client.

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

ErrorMapper

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

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

Middleware

Middleware adds request middleware to the client.

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

Proxy

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

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

ProxyFunc

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

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

Redirect

Redirect sets the redirect policy for the client.

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

Transport

Transport wraps the underlying transport with a custom RoundTripper.

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

Debugging

Dump

Dump prints values using the bundled godump formatter.

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

DumpAll

DumpAll prints the request and response for every call made by a client.

client := httpclient.New(httpclient.DumpAll())
_, err := client.Get[string](context.Background(), "https://httpbin.org/base64/aGVsbG8=")
if err != nil {
	log.Fatal(err)
}

DumpEachRequest

DumpEachRequest buffers a dump for each request on the client. Read each buffered dump with the underlying req response's Dump method.

client := httpclient.New(httpclient.DumpEachRequest())
resp, err := client.Req().R().Get("https://httpbin.org/base64/aGVsbG8=")
if err != nil {
	log.Fatal(err)
}
fmt.Print(resp.Dump())

DumpEachRequestTo

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

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

DumpTo

DumpTo writes a single request and response to the given writer.

client := httpclient.New()
_, err := client.Get[string](context.Background(),
	"https://httpbin.org/base64/aGVsbG8=",
	httpclient.DumpTo(os.Stdout),
)
if err != nil {
	log.Fatal(err)
}
// :authority: httpbin.org
// :method: GET
// :path: /base64/aGVsbG8=
// :scheme: https
// user-agent: httpclient (https://github.com/goforj/httpclient)
// accept-encoding: gzip
//
// :status: 200
// access-control-allow-credentials: true
// access-control-allow-origin: *
// access-control-expose-headers: Retry-After, RateLimit, RateLimit-Policy, WWW-Authenticate
// content-length: 5
// content-type: text/plain; charset=utf-8
// x-content-type-options: nosniff
// date: Thu, 03 Dec 2026 09:18:35 GMT
//
// hello

DumpToFile

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

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

EnableDump

EnableDump buffers a single request and response in memory. Read the buffered output with the underlying req response's Dump method.

client := httpclient.New()
_, err := client.Get[string](context.Background(), "https://httpbin.org/base64/aGVsbG8=",
	httpclient.EnableDump(),
	httpclient.Before(func(r *req.Request) {
		r.OnAfterResponse(func(_ *req.Client, resp *req.Response) error {
			fmt.Print(resp.Dump())
			return nil
		})
	}),
)
if err != nil {
	log.Fatal(err)
}

OptionBuilder.DumpToFile

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

Trace

Trace collects network timings for a single request.

client := httpclient.New()
var request *req.Request
_, err := client.Get[string](context.Background(), "https://httpbin.org/base64/aGVsbG8=",
	httpclient.Trace(),
	httpclient.Before(func(r *req.Request) {
		request = r
	}),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Total:", request.TraceInfo().TotalTime.Round(time.Millisecond))
// Total: 124ms

TraceAll

TraceAll collects network timings for each request on the client.

client := httpclient.New(httpclient.TraceAll())
resp, err := client.Req().R().Get("https://httpbin.org/base64/aGVsbG8=")
if err != nil {
	log.Fatal(err)
}
timing := resp.TraceInfo()
fmt.Printf("DNS %s, TLS %s, first byte %s, total %s\n",
	timing.DNSLookupTime.Round(time.Millisecond), timing.TLSHandshakeTime.Round(time.Millisecond),
	timing.FirstResponseTime.Round(time.Millisecond), timing.TotalTime.Round(time.Millisecond))
// DNS 67ms, TLS 49ms, first byte 34ms, total 186ms

Download Options

OutputFile

OutputFile streams the response body to a file path.

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

Errors

HTTPError.Error

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

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

Request Composition

Body

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

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

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

Form

Form sets form data for the request.

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

Header

Header sets a header on a request or client.

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

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

Headers

Headers sets multiple headers on a request or client.

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

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

JSON

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

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

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

Path

Path sets a path parameter by name.

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

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

Paths

Paths sets multiple path parameters from a map.

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

Queries

Queries sets query parameters from a map.

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

Query

Query adds query parameters as key/value pairs.

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

UserAgent

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

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

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

Request Control

Before

Before runs a hook before the request is sent.

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

Timeout

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

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

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

Requests

Client.Delete

Delete issues a DELETE request and decodes its response.

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

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

Client.Get

Get issues a GET request and decodes its response.

Example: bind to a struct

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

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

Example: read a string body using the same client

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

Client.Head

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

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

Client.Options

Options issues an OPTIONS request and decodes its response.

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

Client.Patch

Patch issues a PATCH request and decodes its response.

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

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

Client.Post

Post issues a POST request and decodes its response.

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

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

Client.Put

Put issues a PUT request and decodes its response.

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

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

Client.Send

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

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

Do

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

r := req.C().R().SetHeader("X-Trace", "1")
r.SetURL("https://httpbin.org/headers")
r.Method = http.MethodGet

res, rawResp, err := httpclient.Do[map[string]any](context.Background(), r)
if err != nil {
	return
}
httpclient.Dump(res)
// #map[string]interface {} {
//   headers => #map[string]interface {} {
//     X-Trace => "1" #string
//   }
// }
println(rawResp.StatusCode)

Retry

RetryBackoff

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

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

RetryCondition

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

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

RetryCount

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

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

RetryFixedInterval

RetryFixedInterval sets the delay between retry attempts.

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

RetryHook

RetryHook registers a callback that runs before each retry attempt.

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

RetryInterval

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

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

Retry (Client)

Retry

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

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

Upload Options

File

File attaches a file from disk as multipart form data.

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

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

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

FileBytes

FileBytes attaches a file from bytes as multipart form data.

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

FileReader

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

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

Files

Files attaches multiple files from disk as multipart form data.

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

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

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

UploadCallback

UploadCallback registers a callback for upload progress.

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	httpclient.UploadCallback(func(info req.UploadInfo) {
		percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
		fmt.Printf("\rprogress: %.1f%%", percent)
		if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
			fmt.Print("\n")
		}
	}),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

UploadCallbackWithInterval

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

client := httpclient.New()
res, err := client.Post[map[string]any](context.Background(), "https://httpbin.org/post", nil,
	httpclient.FileBytes("file", "report.txt", []byte("hello")),
	httpclient.UploadCallbackWithInterval(func(info req.UploadInfo) {
		percent := float64(info.UploadedSize) / float64(info.FileSize) * 100
		fmt.Printf("\rprogress: %.1f%% (%.0f bytes)", percent, float64(info.UploadedSize))
		if info.FileSize > 0 && info.UploadedSize >= info.FileSize {
			fmt.Print("\n")
		}
	}, 200*time.Millisecond),
)
if err != nil {
	log.Fatal(err)
}
httpclient.Dump(res["files"])
// #map[string]interface {} {
//    file => "hello" #string
// }

UploadProgress

UploadProgress enables a default progress spinner and bar for uploads.

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

Development

Run these commands from the repository root.

make test     # Run tests and compile the examples.
make vet      # Run static checks.
make generate # Refresh the README and example programs.

Edit GoDoc for the API examples and the programs in examples/quick-start and examples/testing for their embedded snippets. The test suite checks the output of examples that use the recording transport. Run make help for the full list of targets.

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

Jelajahi proyek terkait

Memuat…