Documentation
¶
Index ¶
- Constants
- func GetClientConfigKey(name string) string
- type CircuitBreakerSettings
- type CircuitIsOpenError
- type Client
- func NewCircuitBreakerClientWithInterfaces(baseClient Client, logger log.Logger, clock clock.Clock, name string, ...) Client
- func NewHttpClientWithInterfaces(logger log.Logger, clock clock.Clock, metricWriter metric.Writer, ...) Client
- func ProvideHttpClient(ctx context.Context, config cfg.Config, logger log.Logger, name string, ...) (Client, error)
- type ClientOption
- type DialerOption
- type DialerSettings
- type Header
- type InstrumentationSettings
- type Option
- func WithAdditionalRootCAFromPEM(pemData []byte) Option
- func WithClientCertificates(certs ...tls.Certificate) Option
- func WithClientOption(option ClientOption) Option
- func WithDialerKeepAlive(keepAlive time.Duration) Option
- func WithDialerOption(option DialerOption) Option
- func WithDialerTimeout(timeout time.Duration) Option
- func WithForceHTTP2(force bool) Option
- func WithInsecureSkipVerify(skip bool) Option
- func WithMinTLSVersion(version uint16) Option
- func WithProxy(proxy func(request *http.Request) (*netUrl.URL, error)) Option
- func WithRootCAs(rootCAs *x509.CertPool) Option
- func WithServerName(name string) Option
- func WithTransportOption(option TransportOption) Option
- func WithUrlValidator(validator UrlValidator) Option
- type Request
- func (r *Request) GetBody() any
- func (r *Request) GetError() error
- func (r *Request) GetHeader() Header
- func (r *Request) GetToken() string
- func (r *Request) GetUrl() string
- func (r *Request) WithAuthToken(token string) *Request
- func (r *Request) WithBasicAuth(username string, password string) *Request
- func (r *Request) WithBody(body any) *Request
- func (r *Request) WithForwardTraceId(forwardTraceId bool) *Request
- func (r *Request) WithHeader(key string, value string) *Request
- func (r *Request) WithMultipartFile(param, fileName string, reader io.Reader) *Request
- func (r *Request) WithMultipartFormData(params url.Values) *Request
- func (r *Request) WithOutputFile(path string) *Request
- func (r *Request) WithQueryMap(values any) *Request
- func (r *Request) WithQueryObject(obj any) *Request
- func (r *Request) WithQueryParam(key string, values ...any) *Request
- func (r *Request) WithUrl(rawUrl string) *Request
- type Resolver
- type ResolverSettings
- type Response
- type RetryAfterSettings
- type RetryConditionFunc
- type Settings
- type TracingSettings
- type TransportOption
- type TransportSettings
- type UrlValidationSettings
- type UrlValidator
Constants ¶
const ( DeleteRequest = "DELETE" GetRequest = "GET" PostRequest = "POST" PutRequest = "PUT" PatchRequest = "PATCH" OptionsRequest = "OPTIONS" )
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 ¶
Types ¶
type CircuitBreakerSettings ¶
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
}
type ClientOption ¶ added in v0.67.0
type ClientOption func(client *client) error
type DialerOption ¶ added in v0.67.0
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 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
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
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
WithDialerTimeout sets the maximum amount of time a dial will wait for a connection to complete.
func WithForceHTTP2 ¶ added in v0.67.0
WithForceHTTP2 controls whether the client attempts to use HTTP/2 without explicit registration.
func WithInsecureSkipVerify ¶ added in v0.67.0
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
WithMinTLSVersion sets the minimum TLS version the client accepts, e.g. tls.VersionTLS13.
func WithProxy ¶ added in v0.67.0
WithProxy sets the proxy function of the transport. Use a nil proxy to disable proxying.
func WithRootCAs ¶ added in v0.67.0
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
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 ¶
NewJsonRequest creates a request that already contains the application/json content-type, don't create the object inline!
func NewRequest ¶
NewRequest or client.NewRequest() creates a request, don't create the object inline!
func NewXmlRequest ¶
NewXmlRequest creates a request that already contains the application/xml content-type, don't create the object inline!
func (*Request) WithAuthToken ¶
func (*Request) WithBasicAuth ¶
func (*Request) WithForwardTraceId ¶ added in v0.29.0
WithForwardTraceId allows you to configure whether you want to add the trace ID header to the downstream systems
func (*Request) WithMultipartFile ¶
func (*Request) WithMultipartFormData ¶
func (*Request) WithOutputFile ¶
func (*Request) WithQueryMap ¶
func (*Request) WithQueryObject ¶
func (*Request) WithQueryParam ¶
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 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 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"`
}
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 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