httputil

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 39 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.

Documentation

Index

Constants

View Source
const (
	// Waiting for a free connection from the pool
	PhasePool = "pool"
	// Name lookup, dialing, a proxy tunnel and the TLS handshake
	PhaseConnect = "connect"
	// Sending the request, the limit restarting each time the connection takes more of the body
	PhaseWrite = "write"
	// Waiting for the response, then each read of its body, the limit restarting with every read and not running while the caller holds the body between reads
	PhaseRead = "read"
)

Phases of one exchange a Timeout limits

View Source
const MaxRedirects = 30

Redirects a client following them takes before it gives up

Variables

View Source
var ErrTooManyRedirects = errors.New("stopped after " + strconv.Itoa(MaxRedirects) + " redirects")

Redirect chain longer than MaxRedirects

Functions

func Client

func Client(follow bool) *http.Client

Client sending through Transport, following redirects only when follow is true

func DecodeContent

func DecodeContent(h http.Header, body []byte) ([]byte, error)

Body with the Content-Encoding codings the header lists undone from the last to the first: gzip, deflate, br and zstd; decoding stops at a coding it does not know, which leaves that layer and every one beneath it as they are

func DecodeText

func DecodeText(h http.Header, body []byte) string

Text of a body in the charset its Content-Type names, UTF-8 when it names none or one that is unknown, undecodable bytes as U+FFFD

func DecodingTransport

func DecodingTransport(base http.RoundTripper) http.RoundTripper

Transport asking for gzip, deflate, br and zstd content when a request names no Accept-Encoding of its own, handing back every response body with those codings undone and its Content-Encoding and Content-Length removed, and sending no Authorization or Proxy-Authorization header on a redirect hop once the chain has left the origin of its first request (an upgrade of the same host from http on port 80 to https on port 443 not counting), whatever redirect policy the client follows

func EnvProxies

func EnvProxies() map[string]string

Scheme to proxy URL map the environment alone sets, empty when it sets no proxy

func IsCertificateError

func IsCertificateError(err error) bool

Whether err holds a certificate the client refused: an unknown authority, a name or address it does not cover, a validity period the clock is outside of, or another chain check

func JSONBody

func JSONBody(v any) ([]byte, error)

Request body of v as compact UTF-8 JSON, object keys in their order, an error for a NaN or infinite number anywhere in it

func MergeQuery

func MergeQuery(rawURL string, query url.Values) string

URL with the values merged into its query string, each key given replacing every value the URL carried for it, the query encoded with sorted keys and the fragment kept

func NoProxyBypass

func NoProxyBypass(noProxy, host string) bool

Whether a NO_PROXY style list exempts the host, given with or without a port: comma separated names matching themselves and their subdomains, a leading dot or *. matching subdomains only, IP addresses and CIDR ranges, each with an optional port, * matching every host, loopback hosts always exempt

func Proxies

func Proxies() map[string]string

Scheme to proxy URL map with keys http and https, from the environment when it sets any proxy, else from the operating system

func Proxy

func Proxy(req *http.Request) (*url.URL, error)

Proxy for a request: the http_proxy, https_proxy and all_proxy variables when any is set, else the operating system settings; nil for a host NO_PROXY, the system bypass list or a loopback address exempts, an error for a proxy setting that cannot be used

func ProxyBypass

func ProxyBypass(host string) bool

Whether the bypass list exempts the host, given with or without a port: NO_PROXY, the operating system list when the environment sets no proxy, and loopback hosts always

func RedirectPolicy

func RedirectPolicy(follow bool) func(*http.Request, []*http.Request) error

Redirect policy following up to MaxRedirects hops, the Authorization, Proxy-Authorization and Cookie headers the first request carried dropped from every hop once the chain has left that origin (an upgrade of the same host from http on port 80 to https on port 443 not counting); or handing back each redirect response itself when follow is false

func RetryAfter

func RetryAfter(h http.Header) (time.Duration, bool)

Wait the Retry-After header asks for, as delay seconds or an HTTP date, never negative; false when the header is absent or unreadable

func RetryAfterValue

func RetryAfterValue(v any) (time.Duration, bool)

Wait a Retry-After value of any decoded type asks for: a number of seconds, or text read as the header is; false for nil, booleans and anything else

func SystemProxies

func SystemProxies() map[string]string

Scheme to proxy URL map the operating system settings hold, empty on a platform that keeps none

func SystemProxyBypass

func SystemProxyBypass(host string) bool

Whether the operating system bypass list exempts the host, given with or without a port

func TimeoutTransport

func TimeoutTransport(base http.RoundTripper, t Timeout) http.RoundTripper

Transport holding each request to the phase limits in t, the read limit restarting with every body read and not running between reads; a request that runs out of a limit fails with a *TimeoutError

func Transport

func Transport() http.RoundTripper

Process wide transport: the settings of http.DefaultTransport with the proxy Proxy picks for each request and dials following the address family preference, connections pooled across every caller

func TrustEnvCA

func TrustEnvCA(t *http.Transport) http.RoundTripper

Transport trusting the CA bundle file or directory REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE names on top of the roots t trusts, t itself when neither is set or t skips verification, http.DefaultTransport standing in for a nil t; a bundle that cannot be loaded fails every TLS handshake with the reason

Types

type Response

type Response struct {
	StatusCode int
	// Status line text after the protocol, such as "404 Not Found", empty when the response was not read from the wire
	Status string
	Header http.Header
	// URL of the request that produced the response, the last hop when redirects were followed
	URL string
	// Body bytes, the content codings the transport undid already undone
	Content []byte
}

Response read whole: the status, the headers, the URL that answered and the body bytes

func Do

func Do(client *http.Client, req *http.Request, t Timeout) (*Response, error)

Sends req through client with every phase held to its limit in t and reads the whole body; every failure is a *url.Error whose cause is a *TimeoutError when a limit ran out

func (*Response) CheckStatus

func (r *Response) CheckStatus() error

Status error of the response, nil when the status is in the 2xx range

func (*Response) JSON

func (r *Response) JSON() (any, error)

Body decoded as JSON: objects as *jsonutil.Object, arrays as []any, integers that fit as int64, other numbers as float64

func (*Response) Text

func (r *Response) Text() string

Body as text in the charset the Content-Type names, UTF-8 otherwise, undecodable bytes as U+FFFD

type StatusError

type StatusError struct {
	StatusCode int
	// Status line text such as "404 Not Found", the standard text of the code when empty
	Status string
	URL    string
	// Location header of a redirect response, empty otherwise
	Location string
}

Response whose status reports a failure: the code, the status line text, the URL that answered and where a redirect points

func (*StatusError) Error

func (e *StatusError) Error() string

Kind of status, the status line, the URL and for a redirect its target, such as "client error 404 Not Found for https://example.com/x", a password in either URL written as xxxxx

type StreamResponse

type StreamResponse struct {
	Response
	Body io.ReadCloser
	// contains filtered or unexported fields
}

Response with its body still open: each read must return within the read limit, time between reads not counted, and Close ends the exchange

func Stream

func Stream(client *http.Client, req *http.Request, t Timeout) (*StreamResponse, error)

Sends req through client with every phase held to its limit in t and hands back the response with its body open; the caller closes it

type Timeout

type Timeout struct{ Connect, Read, Write, Pool time.Duration }

Limits of the phases of one exchange, a zero or negative limit never firing

func EachPhase

func EachPhase(d time.Duration) Timeout

Timeout giving every phase the same limit, none at all when d is not positive

type TimeoutError

type TimeoutError struct {
	Phase string
	// Limit that ran out, zero when unknown
	Limit time.Duration
}

Phase of an exchange that outlasted its limit

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

The phase that timed out and its limit, such as "read timed out after 30s"

func (*TimeoutError) Is

func (e *TimeoutError) Is(target error) bool

Whether target is context.DeadlineExceeded or os.ErrDeadlineExceeded, the deadline errors a phase limit stands for

func (*TimeoutError) Temporary

func (e *TimeoutError) Temporary() bool

Always true: the same request may succeed when sent again

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Always true: the error is a timeout

Jump to

Keyboard shortcuts

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