http

package
v0.29.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2024 License: MIT Imports: 25 Imported by: 0

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"
	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,
) Client

func ProvideHttpClient

func ProvideHttpClient(ctx context.Context, config cfg.Config, logger log.Logger, name string) (Client, 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 connect to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is no 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"`

	// DualStack previously enabled RFC 6555 Fast Fallback
	// support, also known as "Happy Eyeballs", in which IPv4 is
	// tried soon if IPv6 appears to be misconfigured and
	// hanging.
	//
	// Deprecated: Fast Fallback is enabled by default. To
	// disable, set FallbackDelay to a negative value.
	DualStack bool `cfg:"dual_stack" default:"true"`

	// FallbackDelay specifies the length of time to wait before
	// spawning a 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 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() interface{}

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 interface{}) *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 interface{}) *Request

func (*Request) WithQueryObject

func (r *Request) WithQueryObject(obj interface{}) *Request

func (*Request) WithQueryParam

func (r *Request) WithQueryParam(key string, values ...interface{}) *Request

func (*Request) WithUrl

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

type Response

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

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"`
	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"`
}

func UnmarshalClientSettings

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

type TracingSettings added in v0.29.0

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

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"`

	// 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 DialerSettings `cfg:"dialer"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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