http

package
v0.69.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 32 Imported by: 1

Documentation

Index

Constants

View Source
const (
	DeleteRequest  = "DELETE"
	GetRequest     = "GET"
	PostRequest    = "POST"
	PutRequest     = "PUT"
	PatchRequest   = "PATCH"
	OptionsRequest = "OPTIONS"
)
View Source
const (
	AcceptAll               = "*/*"
	AuthorizationTypeBasic  = "Basic"
	AuthorizationTypeBearer = "Bearer"
	AuthorizationTypeDigest = "Digest"

	ContentEncodingGzip = "gzip"

	MimeTypeApplicationFormUrlencoded = "application/x-www-form-urlencoded"
	MimeTypeApplicationJson           = "application/json"
	MimeTypeApplicationOctetStream    = "application/octet-stream"
	MimeTypeApplicationXml            = "application/xml"
	MimeTypeTextCsv                   = "text/csv"
	MimeTypeTextPlain                 = "text/plain"
)

Variables

This section is empty.

Functions

func GetClientConfigKey

func GetClientConfigKey(name string) string

Types

type CircuitBreakerSettings

type CircuitBreakerSettings struct {
	Enabled          bool          `cfg:"enabled" default:"false"`
	MaxFailures      int64         `cfg:"max_failures" default:"10"`
	RetryDelay       time.Duration `cfg:"retry_delay" default:"1m"`
	ExpectedStatuses []int         `cfg:"expected_statuses"`
}

type CircuitIsOpenError

type CircuitIsOpenError struct{}

func (CircuitIsOpenError) Error

func (c CircuitIsOpenError) Error() string

type Client

type Client interface {
	Delete(ctx context.Context, request *Request) (*Response, error)
	Get(ctx context.Context, request *Request) (*Response, error)
	Patch(ctx context.Context, request *Request) (*Response, error)
	Post(ctx context.Context, request *Request) (*Response, error)
	Put(ctx context.Context, request *Request) (*Response, error)
	SetTimeout(timeout time.Duration)
	SetUserAgent(ua string)
	SetProxyUrl(p string)
	SetCookies(cs []*http.Cookie)
	SetCookie(c *http.Cookie)
	SetRedirectValidator(allowRequest func(request *http.Request) bool)
	AddRetryCondition(f RetryConditionFunc)
	NewRequest() *Request
	NewJsonRequest() *Request
	NewXmlRequest() *Request
}

func NewCircuitBreakerClientWithInterfaces

func NewCircuitBreakerClientWithInterfaces(baseClient Client, logger log.Logger, clock clock.Clock, name string, settings CircuitBreakerSettings) Client

func NewHttpClientWithInterfaces

func NewHttpClientWithInterfaces(
	logger log.Logger,
	clock clock.Clock,
	metricWriter metric.Writer,
	httpClient restyClient,
	forwardTraceId bool,
	requestTimeout time.Duration,
	urlValidator UrlValidator,
) Client

func ProvideHttpClient

func ProvideHttpClient(ctx context.Context, config cfg.Config, logger log.Logger, name string, options ...Option) (Client, error)

type ClientOption added in v0.67.0

type ClientOption func(client *client) error

type DialerOption added in v0.67.0

type DialerOption func(dialer *net.Dialer) error

type DialerSettings added in v0.17.3

type DialerSettings struct {
	// KeepAlive specifies the interval between keep-alive
	// probes for an active network connection.
	// If zero, keep-alive probes are sent with a default value
	// (currently 15 seconds), if supported by the protocol and operating
	// system. Network protocols or operating systems that do
	// not support keep-alives ignore this field.
	// If negative, keep-alive probes are disabled.
	KeepAlive time.Duration `cfg:"keep_alive" default:"30s"`

	// Timeout is the maximum amount of time a dial will wait for
	// a connection to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is a 30 seconds timeout.
	//
	// When using TCP and dialing a host name with multiple IP
	// addresses, the timeout may be divided between them.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	Timeout time.Duration `cfg:"timeout" default:"30s"`

	// FallbackDelay specifies the length of time to wait before
	// spawning an RFC 6555 Fast Fallback connection. That is, this
	// is the amount of time to wait for IPv6 to succeed before
	// assuming that IPv6 is misconfigured and falling back to
	// IPv4.
	//
	// If zero, a default delay of 300ms is used.
	// A negative value disables Fast Fallback support.
	FallbackDelay time.Duration `cfg:"fallback_delay" default:"0s"`
}
type Header map[string][]string

type InstrumentationSettings added in v0.30.0

type InstrumentationSettings struct {
	Enabled bool `cfg:"enabled" default:"false"`
}

type Option added in v0.67.0

type Option struct {
	ClientOption    ClientOption
	DialerOption    DialerOption
	TransportOption TransportOption
}

func WithAdditionalRootCAFromPEM added in v0.67.0

func WithAdditionalRootCAFromPEM(pemData []byte) Option

WithAdditionalRootCAFromPEM appends the PEM encoded certificates in pemData to the system certificate pool and uses the result as the RootCAs of the client. Use this to trust additional, e.g. internal, certificate authorities without replacing the system defaults.

func WithClientCertificates added in v0.67.0

func WithClientCertificates(certs ...tls.Certificate) Option

WithClientCertificates configures the client certificates used for mutual TLS authentication.

func WithClientOption added in v0.67.0

func WithClientOption(option ClientOption) Option

func WithDialerKeepAlive added in v0.67.0

func WithDialerKeepAlive(keepAlive time.Duration) Option

WithDialerKeepAlive sets the interval between keep-alive probes for an active network connection.

func WithDialerOption added in v0.67.0

func WithDialerOption(option DialerOption) Option

func WithDialerTimeout added in v0.67.0

func WithDialerTimeout(timeout time.Duration) Option

WithDialerTimeout sets the maximum amount of time a dial will wait for a connection to complete.

func WithForceHTTP2 added in v0.67.0

func WithForceHTTP2(force bool) Option

WithForceHTTP2 controls whether the client attempts to use HTTP/2 without explicit registration.

func WithInsecureSkipVerify added in v0.67.0

func WithInsecureSkipVerify(skip bool) Option

WithInsecureSkipVerify controls whether the client verifies the server's TLS certificates. If skip is true, certificate expiry, hostname matching and unknown certificate authorities are all ignored, which exposes the connection to man-in-the-middle attacks.

WARNING: Only use this in development or test environments, or against trusted networks with self-signed certificates. If possible, consider using WithAdditionalRootCAFromPEM instead to add your custom CA instead.

func WithMinTLSVersion added in v0.67.0

func WithMinTLSVersion(version uint16) Option

WithMinTLSVersion sets the minimum TLS version the client accepts, e.g. tls.VersionTLS13.

func WithProxy added in v0.67.0

func WithProxy(proxy func(request *http.Request) (*netUrl.URL, error)) Option

WithProxy sets the proxy function of the transport. Use a nil proxy to disable proxying.

func WithRootCAs added in v0.67.0

func WithRootCAs(rootCAs *x509.CertPool) Option

WithRootCAs completely replaces the pool of root CAs with the given one. To just add a singular CA, consider using WithAdditionalRootCAFromPEM instead.

func WithServerName added in v0.67.0

func WithServerName(name string) Option

WithServerName overrides the name used to authenticate the remote server and included in the Server Name Indication (SNI) extension of the TLS handshake.

func WithTransportOption added in v0.67.0

func WithTransportOption(option TransportOption) Option

func WithUrlValidator added in v0.67.0

func WithUrlValidator(validator UrlValidator) Option

WithUrlValidator installs a custom UrlValidator on the client. When set, it takes precedence over the validator derived from the url_validation config and every request (including all redirects) is validated before being sent.

type Request

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

func NewJsonRequest

func NewJsonRequest(client Client) *Request

NewJsonRequest creates a request that already contains the application/json content-type, don't create the object inline!

func NewRequest

func NewRequest(client Client) *Request

NewRequest or client.NewRequest() creates a request, don't create the object inline!

func NewXmlRequest

func NewXmlRequest(client Client) *Request

NewXmlRequest creates a request that already contains the application/xml content-type, don't create the object inline!

func (*Request) GetBody

func (r *Request) GetBody() any

func (*Request) GetError

func (r *Request) GetError() error

func (*Request) GetHeader

func (r *Request) GetHeader() Header

func (*Request) GetToken

func (r *Request) GetToken() string

func (*Request) GetUrl

func (r *Request) GetUrl() string

func (*Request) WithAuthToken

func (r *Request) WithAuthToken(token string) *Request

func (*Request) WithBasicAuth

func (r *Request) WithBasicAuth(username string, password string) *Request

func (*Request) WithBody

func (r *Request) WithBody(body any) *Request

func (*Request) WithForwardTraceId added in v0.29.0

func (r *Request) WithForwardTraceId(forwardTraceId bool) *Request

WithForwardTraceId allows you to configure whether you want to add the trace ID header to the downstream systems

func (*Request) WithHeader

func (r *Request) WithHeader(key string, value string) *Request

func (*Request) WithMultipartFile

func (r *Request) WithMultipartFile(param, fileName string, reader io.Reader) *Request

func (*Request) WithMultipartFormData

func (r *Request) WithMultipartFormData(params url.Values) *Request

func (*Request) WithOutputFile

func (r *Request) WithOutputFile(path string) *Request

func (*Request) WithQueryMap

func (r *Request) WithQueryMap(values any) *Request

func (*Request) WithQueryObject

func (r *Request) WithQueryObject(obj any) *Request

func (*Request) WithQueryParam

func (r *Request) WithQueryParam(key string, values ...any) *Request

func (*Request) WithUrl

func (r *Request) WithUrl(rawUrl string) *Request

type Resolver added in v0.67.0

type Resolver interface {
	LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
}

Resolver resolves hostnames to ip addresses.

type ResolverSettings added in v0.40.6

type ResolverSettings struct {
	// KeepAlive specifies the interval between keep-alive
	// probes for an active network connection.
	// If zero, keep-alive probes are sent with a default value
	// (currently 15 seconds), if supported by the protocol and operating
	// system. Network protocols or operating systems that do
	// not support keep-alives ignore this field.
	// If negative, keep-alive probes are disabled.
	KeepAlive time.Duration `cfg:"keep_alive" default:"30s"`

	// Timeout is the maximum amount of time a dial will wait for
	// a connection to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is a 30 seconds timeout.
	//
	// When using TCP and dialing a host name with multiple IP
	// addresses, the timeout may be divided between them.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	Timeout time.Duration `cfg:"timeout" default:"30s"`

	// DnsServers allow you to specify a set of DNS servers to use
	// instead of using the system defaults. Setting this allows
	// you to avoid resolving internal hostnames (for example, when
	// running inside a cloud environment).
	//
	// Syntax can be either an IP address (8.8.8.8) or an IP address
	// followed by a port number (8.8.8.8:53).
	DnsServers []string `cfg:"dns_servers"`
}

func (ResolverSettings) GetResolver added in v0.40.6

func (s ResolverSettings) GetResolver() *net.Resolver

type Response

type Response struct {
	Body            []byte
	Header          http.Header
	Cookies         []*http.Cookie
	StatusCode      int
	RequestDuration time.Duration
	TotalDuration   *time.Duration
}

type RetryAfterSettings added in v0.62.1

type RetryAfterSettings struct {
	DefaultWaitTime time.Duration `cfg:"default_wait_time" default:"1s" validate:"min=0"`
	JitterMin       float64       `cfg:"jitter_min" default:"1" validate:"min=1"`
	JitterMax       float64       `cfg:"jitter_max" default:"1.5" validate:"min=1"`
}

RetryAfterSettings configures how the HTTP client handles Retry-After headers on retried responses.

type RetryConditionFunc

type RetryConditionFunc func(*Response, error) bool

type Settings

type Settings struct {
	DisableCookies         bool                   `cfg:"disable_cookies" default:"false"`
	FollowRedirects        bool                   `cfg:"follow_redirects" default:"true"`
	RequestTimeout         time.Duration          `cfg:"request_timeout" default:"30s"`
	RetryCount             int                    `cfg:"retry_count" default:"5"`
	RetryAfterSettings     RetryAfterSettings     `cfg:"retry_after"`
	RetryMaxWaitTime       time.Duration          `cfg:"retry_max_wait_time" default:"2000ms"`
	RetryResetReaders      bool                   `cfg:"retry_reset_readers" default:"true"`
	RetryWaitTime          time.Duration          `cfg:"retry_wait_time" default:"100ms"`
	CircuitBreakerSettings CircuitBreakerSettings `cfg:"circuit_breaker"`
	TransportSettings      TransportSettings      `cfg:"transport"`
	TracingSettings        TracingSettings        `cfg:"tracing"`
	UrlValidationSettings  UrlValidationSettings  `cfg:"url_validation"`
}

func UnmarshalClientSettings

func UnmarshalClientSettings(config cfg.Config, name string) (Settings, error)

type TracingSettings added in v0.29.0

type TracingSettings struct {
	ForwardTraceId  bool                    `cfg:"forward_trace_id" default:"false"`
	Instrumentation InstrumentationSettings `cfg:"instrumentation"`
}

type TransportOption added in v0.67.0

type TransportOption func(transport *http.Transport) error

type TransportSettings added in v0.17.3

type TransportSettings struct {
	// TLSHandshakeTimeout specifies the maximum amount of time to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration `cfg:"tls_handshake_timeout" default:"10s"`

	// InsecureSkipVerify controls whether the http client verifies
	// the server's TLS certificates. If true, certificate expiry,
	// hostname matching and unknown certificate authorities are all
	// ignored, which exposes the connection to man-in-the-middle
	// attacks.
	//
	// WARNING: Only enable this in development or test environments,
	// or against trusted networks with self-signed certificates.
	InsecureSkipVerify bool `cfg:"insecure_skip_verify" default:"false"`

	// DisableKeepAlives, if true, disables HTTP keep-alives and
	// will only use the connection to the server for a single
	// HTTP request.
	//
	// This is unrelated to the similarly named TCP keep-alives.
	DisableKeepAlives bool `cfg:"disable_keep_alives" default:"false"`

	// DisableCompression, if true, prevents the Transport from
	// requesting compression with an "Accept-Encoding: gzip"
	// request header when the Request contains no existing
	// Accept-Encoding value. If the Transport requests gzip on
	// its own and gets a gzipped response, it's transparently
	// decoded in the Response.Body. However, if the user
	// explicitly requested gzip it is not automatically
	// uncompressed.
	DisableCompression bool `cfg:"disable_compression" default:"false"`

	// MaxIdleConns controls the maximum number of idle (keep-alive)
	// connections across all hosts. Zero means no limit.
	MaxIdleConns int `cfg:"max_idle_conns" default:"100"`

	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
	// (keep-alive) connections to keep per-host. If zero,
	// GOMAXPROCS+1 is used.
	MaxIdleConnsPerHost int `cfg:"max_idle_conns_per_host" default:"0"`

	// MaxConnsPerHost optionally limits the total number of
	// connections per host, including connections in the dialing,
	// active, and idle states. On limit violation, dials will block.
	//
	// Zero means no limit.
	MaxConnsPerHost int `cfg:"max_conns_per_host" default:"0"`

	// IdleConnTimeout is the maximum amount of time an idle
	// (keep-alive) connection will remain idle before closing
	// itself.
	// Zero means no limit.
	IdleConnTimeout time.Duration `cfg:"idle_conn_timeout" default:"90s"`

	// ResponseHeaderTimeout, if non-zero, specifies the amount of
	// time to wait for a server's response headers after fully
	// writing the request (including its body, if any). This
	// time does not include the time to read the response body.
	ResponseHeaderTimeout time.Duration `cfg:"response_header_timeout" default:"0s"`

	// ExpectContinueTimeout, if non-zero, specifies the amount of
	// time to wait for a server's first response headers after fully
	// writing the request headers if the request has an
	// "Expect: 100-continue" header. Zero means no timeout and
	// causes the body to be sent immediately, without
	// waiting for the server to approve.
	// This time does not include the time to send the request header.
	ExpectContinueTimeout time.Duration `cfg:"expect_continue_timeout" default:"1s"`

	// MaxResponseHeaderBytes specifies a limit on how many
	// response bytes are allowed in the server's response
	// header.
	//
	// Zero means to use a default limit.
	MaxResponseHeaderBytes int64 `cfg:"max_response_header_bytes" default:"0"`

	// WriteBufferSize specifies the size of the write buffer used
	// when writing to the transport.
	// If zero, a default (currently 4KB) is used.
	WriteBufferSize int `cfg:"write_buffer_size" default:"0"`

	// ReadBufferSize specifies the size of the read buffer used
	// when reading from the transport.
	// If zero, a default (currently 4KB) is used.
	ReadBufferSize int `cfg:"read_buffer_size" default:"0"`

	// DialerSettings govern how we establish a TCP connection
	// to the remote host after resolving its IP.
	DialerSettings DialerSettings `cfg:"dialer"`

	// ResolverSettings govern how we resolve the IP of the
	// remote host.
	ResolverSettings ResolverSettings `cfg:"resolver"`
}

type UrlValidationSettings added in v0.67.0

type UrlValidationSettings struct {
	Enabled bool `cfg:"enabled" default:"false"`
}

UrlValidationSettings controls whether the client validates the urls it is asked to fetch. When enabled, every request (and every redirect it follows) is checked to not point at an internal address, and the connection is made to the exact ip addresses the host resolved to at validation time.

type UrlValidator added in v0.67.0

type UrlValidator interface {
	// Validate reports whether the url may be fetched. It rejects anything which is not a plain http(s) url on a standard
	// port whose host resolves to a public address. It returns a list of validated IP addresses the URL was resolved to.
	// The caller is responsible for resolving the hostname to only those IPs when performing a request to the given URL.
	Validate(ctx context.Context, rawUrl string) (ips []net.IPAddr, err error)
}

A UrlValidator checks if a URL can safely be called, meaning it does not:

  • point to an arbitrary IP address
  • resolve to an IP inside our private network
  • point to a non-standard port

func NewNopUrlValidator added in v0.67.0

func NewNopUrlValidator() UrlValidator

func NewUrlValidator added in v0.67.0

func NewUrlValidator() UrlValidator

func NewUrlValidatorWithInterfaces added in v0.67.0

func NewUrlValidatorWithInterfaces(resolver Resolver) UrlValidator

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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