pyhttpx

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 42 Imported by: 0 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

This section is empty.

Variables

View Source
var ErrTooManyRedirects = errors.New("Exceeded maximum allowed redirects.")

ErrTooManyRedirects is the httpx error raised past the client redirect cap

Functions

func DecodeContent

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

Body with every Content-Encoding undone in reverse order as httpx decodes it, unknown codings left as is

func DecodeText

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

Decodes a body like httpx Response.text, the content type charset when known and utf-8 otherwise

func DialWire

func DialWire(ctx context.Context, dial DialFunc, proxyURL *url.URL, network, address string) (net.Conn, error)

Plaintext connection under a wire layer, connected through a SOCKS proxy or over TLS to an HTTPS forward proxy itself

func DialWireTLS

func DialWireTLS(ctx context.Context, dial DialFunc, proxyURL *url.URL, network, address string, cfg *tls.Config) (net.Conn, error)

TLS connection to address under a wire layer, tunnelled through the proxy when one is given, HTTP/1.1 offered by ALPN

func DialWireTLSStyle

func DialWireTLSStyle(ctx context.Context, dial DialFunc, proxyURL *url.URL, network, address string, cfg *tls.Config, style TunnelStyle) (net.Conn, error)

TLS connection to address under a wire layer, its proxy tunnel opened with the CONNECT head of the given stack

func EnvProxy

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

Proxy of a request from the httpx environment mounts, the proxy and bypass variables read when it is sent

func EnvProxyClient

func EnvProxyClient(follow bool) *http.Client

Client like httpx.get with trust_env, each request sent through the environment proxy it reads at send time

func EnvProxyTransport

func EnvProxyTransport() http.RoundTripper

Default transport whose proxy is the environment proxy each request reads at send time

func ErrorText

func ErrorText(err error) string

str of the httpx exception a failed request raises, timeouts and redirects first then the socket error

func ForwardProxy

func ForwardProxy(proxyURL *url.URL) (*url.URL, error)

Forward proxy of a plain HTTP request, an HTTPS proxy given as http for the wire dial TLS

func HeaderGet

func HeaderGet(h http.Header, name, def string) string

Header value as httpx Headers.get returns it, repeated values joined by a comma and space

func HeaderOrder

func HeaderOrder(m map[string]string) []string

Keys of a header map in recorded order, keys added since following in sorted order the way a later dict insert lands last

func JSONBody

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

Body bytes the Python SDKs and httpx write for a json request, dict order kept, compact, non ASCII raw and NaN refused

func MergeHeaderMaps

func MergeHeaderMaps(maps ...map[string]string) map[string]string

Dict merge of the maps left to right, later values winning in the earlier slot and new keys appended, its order recorded

func MergeParams

func MergeParams(rawURL string, params Params) string

URL with params merged into its query like httpx, new keys replacing old ones and the query re-encoded

func OSErrorText

func OSErrorText(err error) string

str of the OSError a socket call raises, the errno form when the cause carries one

func OrderedHeaderMap

func OrderedHeaderMap(lines ...HeaderLine) map[string]string

Header map built from the lines in order, a repeated name keeping its first slot and last value, its order recorded

func PhaseTimeoutTransport

func PhaseTimeoutTransport(base http.RoundTripper, timeout Timeout) http.RoundTripper

PhaseTimeoutTransport gives each request the distinct connect, write, read and pool limits of one httpx.Timeout

func PlainClient

func PlainClient(follow bool) *http.Client

Plain client like httpx.get, no proxy vetting and redirects followed only on request

func PlainProxy

func PlainProxy(proxyURL *url.URL) func(*http.Request) (*url.URL, error)

Forward proxy for an HTTP target and none for HTTPS, whose tunnel the wire TLS dial opens

func ProtocolError

func ProtocolError(rawURL string) string

UnsupportedProtocol text httpx raises before sending, empty when the scheme is http or https

func RaiseForStatusMessage

func RaiseForStatusMessage(status int, rawURL, location string) string

Text of the HTTPStatusError httpx raise_for_status raises for a non 2xx response

func RedirectPolicy

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

Redirect policy following up to the httpx cap of twenty hops, or returning each redirect response

func RequestTarget

func RequestTarget(ctx context.Context) (*url.URL, error)

URL of the request a transport dial serves, an error for a dial made outside a WireTransport

func RequestsProxy

func RequestsProxy(u *url.URL) (*url.URL, error)

Proxy requests picks for a URL from the environment, nil when no_proxy or the urllib bypass exempts the host

func RetryAfterSeconds

func RetryAfterSeconds(h http.Header) (float64, bool)

Seconds a Retry-After header asks for, numeric or HTTP date, clamped at zero, false when absent or unparsable

func RetryAfterText

func RetryAfterText(text string) (float64, bool)

Seconds of a Retry-After text, numeric or HTTP date, clamped at zero, false when blank or unparsable

func RetryAfterValue

func RetryAfterValue(raw any) (float64, bool)

Seconds of a Retry-After value of any JSON type, None and bool false, clamped at zero

func SetHeaderOrder

func SetHeaderOrder(m map[string]string, keys []string)

Records the order a Python dict holding these headers would iterate them in

func TimeoutTransport

func TimeoutTransport(base http.RoundTripper, timeout time.Duration) http.RoundTripper

TimeoutTransport gives each request the connect, write, read and pool limits of an httpx client built with the timeout

func URLLibProxy

func URLLibProxy(u *url.URL) *url.URL

Proxy urllib ProxyHandler sends a request for u through, nil when none is set or proxy_bypass exempts the host

func URLLibPutHost

func URLLibPutHost(u *url.URL) string

Host line http.client putrequest writes itself, the port left off when it is the default of the scheme

func WithWire

func WithWire(req *http.Request, h *Headers) *http.Request

Request writing exactly these header lines, its header map rebuilt from them for readers of the map

Types

type DecodingError

type DecodingError struct{ Err error }

Failure decoding a Content-Encoding the way httpx raises DecodingError

func (*DecodingError) Error

func (e *DecodingError) Error() string

func (*DecodingError) Unwrap

func (e *DecodingError) Unwrap() error

type DialFunc

type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)

Network dial a tunnel or a direct connection runs over

type EnvProxies

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

Proxy mount table an httpx client built with trust_env reads at construction, most specific first

func NewEnvProxies

func NewEnvProxies(proxies map[string]string) (*EnvProxies, error)

Mounts get_environment_proxies builds from a getproxies map, an unknown proxy scheme failing as httpx Proxy fails

func (*EnvProxies) For

func (p *EnvProxies) For(u *url.URL) *url.URL

Proxy the client sends a request for u through, nil for a direct connection

type HeaderLine

type HeaderLine struct{ Name, Value string }

One header line as a Python client writes it, its spelling kept

type Headers

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

Header lines in wire order with the case insensitive editing of httpx Headers

func NewHeaders

func NewHeaders(lines ...HeaderLine) *Headers

Headers holding the lines in the order given

func WireOf

func WireOf(req *http.Request) *Headers

Header lines the request writes, nil for a request built without them

func (*Headers) Del

func (h *Headers) Del(name string)

Drops every line of the name in any case

func (*Headers) Get

func (h *Headers) Get(name string) (string, bool)

First value under the name in any case, false when absent

func (*Headers) HostInPlace

func (h *Headers) HostInPlace() *Headers

Marks the lines as an http.client head whose carried Host keeps its slot

func (*Headers) Lines

func (h *Headers) Lines() []HeaderLine

Copy of the lines in wire order

func (*Headers) Set

func (h *Headers) Set(name, value string)

Replaces the first line of the name in place under the new spelling and drops the rest, else appends

func (*Headers) Update

func (h *Headers) Update(other []HeaderLine)

Pops every name the other lines carry, then appends all of them in their order

type Params

type Params [][2]string

Ordered query parameters as httpx receives them in a params mapping

type Response

type Response struct {
	StatusCode int
	Header     http.Header
	URL        string
	Content    []byte
	// Status line text after the protocol, empty when the response was not read from the wire
	Status string
}

Buffered response with the status, headers, final URL and body bytes

func Do

func Do(client *http.Client, req *http.Request, timeout time.Duration) (*Response, error)

Sends a request with httpx per phase timeouts and reads the whole body

func DoTimeout

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

Sends a request with distinct httpx.Timeout phase limits and reads the whole body

func (*Response) JSON

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

Body parsed by json.loads over the raw bytes

func (*Response) StatusErrorText

func (r *Response) StatusErrorText(rawURL string) string

HTTPStatusError text of this response with the reason phrase its status line carried

func (*Response) Text

func (r *Response) Text() string

Body decoded with the declared charset or utf-8, invalid bytes replaced

type StreamResponse

type StreamResponse struct {
	Response
	Body io.ReadCloser
}

Streamed response whose body reads each restart the read timeout

func Stream

func Stream(client *http.Client, req *http.Request, timeout time.Duration) (*StreamResponse, error)

Sends a request with httpx per phase timeouts and returns the open response stream

func StreamTimeout

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

Sends a request whose connect, write, read and pool phases each get their own httpx.Timeout limit

type Timeout

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

Distinct httpx.Timeout connect, read, write and pool limits, a zero limit never fires

type TimeoutError

type TimeoutError struct{ Phase string }

TimeoutError is the httpx.TimeoutException raised when one request phase outlasts its timeout

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

type TunnelStyle

type TunnelStyle int

CONNECT head a Python HTTP stack writes when it tunnels through a proxy

const (
	// httpcore, Host then Accept then the proxy credentials
	TunnelHTTPCore TunnelStyle = iota
	// http.client set_tunnel as urllib, urllib3, requests and botocore drive it, the proxy credentials then Host
	TunnelHTTPClient
	// urllib HTTPSConnection, plain TCP to the proxy of any scheme, credentials only for a user and password both set
	TunnelURLLib
)

type URLLibRequest

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

Header dicts of a urllib.request.Request, names capitalized as add_header stores them, the unredirected ones apart

func NewURLLibRequest

func NewURLLibRequest(headers ...HeaderLine) *URLLibRequest

Request built with the headers argument in order, each stored under its capitalized name

func (*URLLibRequest) AddHeader

func (r *URLLibRequest) AddHeader(name, value string)

Stores the value under the capitalized name in the redirected headers

func (*URLLibRequest) AddProxyAuthorization

func (r *URLLibRequest) AddProxyAuthorization(proxyURL *url.URL)

Adds the Basic credentials ProxyHandler sends when the proxy URL holds a user and a password

func (*URLLibRequest) AddUnredirectedHeader

func (r *URLLibRequest) AddUnredirectedHeader(name, value string)

Stores the value under the capitalized name in the headers a redirect does not carry

func (*URLLibRequest) DoRequest

func (r *URLLibRequest) DoRequest(host string, data []byte, hasData bool, addheaders []HeaderLine)

Fills the unredirected body headers, Host and opener addheaders the way AbstractHTTPHandler.do_request_ does

func (*URLLibRequest) HasHeader

func (r *URLLibRequest) HasHeader(name string) bool

Whether either dict holds the exact name

func (*URLLibRequest) Header

func (r *URLLibRequest) Header(name string) (string, bool)

Value under the exact name, the redirected headers before the unredirected ones as get_header reads them

func (*URLLibRequest) HeaderItems

func (r *URLLibRequest) HeaderItems() []HeaderLine

Unredirected headers then the redirected ones merged as one dict, header_items order

func (*URLLibRequest) Redirected

func (r *URLLibRequest) Redirected() *URLLibRequest

Request of a redirect hop, the redirected headers without Content-Length and Content-Type as redirect_request copies them

func (*URLLibRequest) RemoveHeader

func (r *URLLibRequest) RemoveHeader(name string)

Pops the exact name from both dicts

func (*URLLibRequest) StripHeaders

func (r *URLLibRequest) StripHeaders(keep map[string]bool)

Keeps only the names whose lowercase form is in keep, both dicts, as _strip_headers drops the rest

func (*URLLibRequest) WireLines

func (r *URLLibRequest) WireLines(method string, putHost string, tunnel bool, body []byte, hasBody bool) *Headers

Head lines http.client writes for the request, Accept-Encoding identity unless set, the do_open dict title cased with Connection close, a body length last

type WireConn

type WireConn struct {
	net.Conn
	// contains filtered or unexported fields
}

Connection that rewrites the head of the next request written on it into the lines its request carries

func NewWireConn

func NewWireConn(c net.Conn) *WireConn

Wire capable connection over a plaintext HTTP connection

func (*WireConn) NetConn

func (c *WireConn) NetConn() net.Conn

Connection under the wire layer for socket level shutdown

func (*WireConn) Write

func (c *WireConn) Write(p []byte) (int, error)

Holds the bytes of an expected request head until it ends, then writes it in wire order with what follows

type WireTransport

type WireTransport struct {
	Base http.RoundTripper
	// Content codings the emulated client decodes, the rest left as received
	Decoders []string
}

Transport writing wire requests and their redirect hops in carried order and undoing the content codings the client advertised

func (WireTransport) CloseIdleConnections

func (t WireTransport) CloseIdleConnections()

Drops the idle connections of the base transport

func (WireTransport) RoundTrip

func (t WireTransport) RoundTrip(req *http.Request) (*http.Response, error)

Writes the request in its carried lines, a redirect hop also dropping each name its redirect policy removed

Jump to

Keyboard shortcuts

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