httpclient

package
v0.0.0-...-acc7a0a Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2025 License: Apache-2.0 Imports: 14 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTimeout                      = errors.New("timeout")
	ErrOverflowMaxWait              = errors.New("overflow max wait")
	ErrOperationContextCanceled     = errors.New("operation context canceled")
	ErrTimeoutAndRetryOptionInvalid = errors.New("retry config invalid")
	ErrMissingURL                   = errors.New("url is missing")
	ErrMissingMethod                = errors.New("method is missing")
	ErrMissingServiceName           = errors.New("missing service name")
)

Functions

func NewSharedPool

func NewSharedPool(opts ...PoolOption) *http.Client

NewSharedPool returns a new http.Client instance with customizable options, ensures the efficient reuse of resources by pooling HTTP connections, thereby reducing overhead and improving performance across multiple clients

Example:

func main() {
	sharedPool := NewSharedPool()

	thirdPartyServiceClient1 := thirdPartyService.NewClient(sharedPool)
	thirdPartyServiceClient2 := thirdPartyService.NewClient(sharedPool)
}

// Inside third party service
func (srv thirdPartyService) Send(ctx context.Context) error {
	srv.sharedPool.Do(ctx,... ) // Implement your logic
}

Refer https://www.loginradius.com/blog/engineering/tune-the-go-http-client-for-high-performance/ NewSharedPool returns a new http.Client instance based on the arguments

Types

type Client

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

A Client describes an HTTP endpoint's client. This client is mainly used to send HTTP request based on the request configuration set into the client and the response handling logic configured within the client.

func NewUnauthenticated

func NewUnauthenticated(cfg Config, pool *SharedCustomPool, opts ...ClientOption) (*Client, error)

NewUnauthenticated returns a new Client instance based on the arguments without any authentication

func (*Client) Send

func (c *Client) Send(ctx context.Context, p Payload) (Response, error)

Send executes an HTTP call based on the information and configuration in the Client

type ClientOption

type ClientOption func(c *Client)

ClientOption alters behaviour of the Client

func DisableRequestBodyLogging

func DisableRequestBodyLogging() ClientOption

DisableRequestBodyLogging method disables the default behaviour of logging request body

func DisableResponseBodyLogging

func DisableResponseBodyLogging() ClientOption

DisableResponseBodyLogging method disables the default behaviour of logging response body

func OverrideBaseRequestHeaders

func OverrideBaseRequestHeaders(m map[string]string) ClientOption

OverrideBaseRequestHeaders method sets a map of request header key-value pairs to the request raised from client

func OverrideContentType

func OverrideContentType(contentType string) ClientOption

OverrideContentType method override default the content type into the request header

func OverrideTimeoutAndRetryOption

func OverrideTimeoutAndRetryOption(maxRetries uint64, maxWaitPerTry, maxWaitInclRetries time.Duration, onTimeout bool, onStatusCodes []int) ClientOption

OverrideTimeoutAndRetryOption method overrides default retry configs if those configs are not zero values

	e.g.
		maxRetries: 3, retry max 3 times after request failed.
		maxWaitPerTry: 10 seconds,
					   request failed
							|
 							2 seconds backoff retry internal wait time
							|
							retry with max 10 seconds wait time
							|
							2 seconds backoff retry internal wait time
							|
							retry with max 10 seconds wait time
							|
							... loop until get request response || reach maxRetries || exceed maxWaitInclRetries.
		maxWaitInclRetries: expected >= 2 seconds + maxRetries * (maxWaitPerTry + 2 seconds), 38 seconds.
							if set to like 30 seconds, will return overflow err at that point before reach maxRetries.
		onTimeout: set to false if no need retry on timeout
		onStatusCodes: [404], retry when get 404 http status code from response

func OverrideUserAgent

func OverrideUserAgent(userAgent string) ClientOption

OverrideUserAgent method override default the user-agent into the request header

type Config

type Config struct {
	ServiceName,
	URL,
	Method string // The HTTP Method to be used
}

Config holds the base config for Client

type MockPoolOption

type MockPoolOption struct {
	mock.Mock
}

MockPoolOption is an autogenerated mock type for the PoolOption type

func NewMockPoolOption

func NewMockPoolOption(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockPoolOption

NewMockPoolOption creates a new instance of MockPoolOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockPoolOption) EXPECT

func (*MockPoolOption) Execute

func (_m *MockPoolOption) Execute(_a0 *http.Client)

Execute provides a mock function with given fields: _a0

type MockPoolOption_Execute_Call

type MockPoolOption_Execute_Call struct {
	*mock.Call
}

MockPoolOption_Execute_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Execute'

func (*MockPoolOption_Execute_Call) Return

func (*MockPoolOption_Execute_Call) Run

func (*MockPoolOption_Execute_Call) RunAndReturn

type MockPoolOption_Expecter

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

func (*MockPoolOption_Expecter) Execute

func (_e *MockPoolOption_Expecter) Execute(_a0 interface{}) *MockPoolOption_Execute_Call

Execute is a helper method to define mock.On call

  • _a0 *http.Client

type Payload

type Payload struct {
	// Request body
	Body []byte
	// QueryParams contains the request/query parameters
	QueryParams url.Values
	// PathVars contains the path variables used to replace placeholders
	// wrapped with {} in Client.URL
	PathVars map[string]string
	// Header contains custom request headers that will be added to the request
	// on http call.
	// The values on this field will override Client.Headers.Values
	Header map[string]string
}

Payload is the request payload struct representation

type PoolOption

type PoolOption func(c *http.Client, t *http.Transport)

PoolOption alters behaviour of the http.Client

func OverridePoolMaxConnsPerHost

func OverridePoolMaxConnsPerHost(n int) PoolOption

OverridePoolMaxConnsPerHost overrides the max conns per host

func OverridePoolMaxIdleConns

func OverridePoolMaxIdleConns(n int) PoolOption

OverridePoolMaxIdleConns overrides the max idle conns

func OverridePoolMaxIdleConnsPerHost

func OverridePoolMaxIdleConnsPerHost(n int) PoolOption

OverridePoolMaxIdleConnsPerHost overrides the max idle conns per host

func OverridePoolTimeoutDuration

func OverridePoolTimeoutDuration(timeout time.Duration) PoolOption

OverridePoolTimeoutDuration overrides the timeout for each try

type Response

type Response struct {
	Status int
	Body   []byte
	Header http.Header
}

Response is the result of the http call

type SharedCustomPool

type SharedCustomPool struct {
	*http.Client
}

SharedCustomPool is a custom wrapper around http.Client that sets the client timeout to zero so that it can be controlled by Client instead.

func NewSharedCustomPool

func NewSharedCustomPool(opts ...PoolOption) *SharedCustomPool

NewSharedCustomPool returns a new custom http.Client instance with custom retry and timeout options based on the arguments

Jump to

Keyboard shortcuts

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