httpclient

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2024 License: MIT Imports: 20 Imported by: 0

README

go-http-client

Installation

go env -w GOPRIVATE=github.com/sinhashubham95/go-http-client
go get github.com/sinhashubham95/go-http-client

Initialisation

Import module
import github.com/sinhashubham95/go-http-client
Initialize go-http-client
Using API

Application must configure http client before making any http call. All endpoint must be configured.

For each http endpoint create a NewRequestConfig. NewRequestConfig provides following tunable properties.

field/method description optional
unique request name A unique name must be passed as parameter to NewRequestConfig. In case of duplicate, latest will replace the previous configuration mandatory
SetTimeout Http timeout mandatory
SetRetryCount Retry count mandatory
SetMethod Http Method (GET, POST etc) mandatory
SetURL Endpoint to call mandatory
SetProxy Proxy URL optional
SetBackoffPolicy Backoff policy - you can choose between ConstantBackoff or ExponentialBackoff optional for NoBackoff
SetHystrixConfig Hystrix Configuration optional
connectTimeout ConnectTimeout is the maximum amount of time a dial will wait for a connect to complete. optional
keepAlive KeepAliveDuration specifies the interval between keep-alive probes for an active network connection optional
maxIdleConnections MaxIdleConnections controls the maximum number of idle (keep-alive) connections across all hosts. Zero means no limit. optional
idleConnectionTimeout IdleConnectionTimeout is the maximum amount of time an idle (keep-alive) connection will remain idle before closing itself. optional
tlsHandshakeTimeout TLSHandshakeTimeout specifies the maximum amount of time waiting to wait for a TLS handshake. mandatory
expectContinueTimeout ExpectContinueTimeout specifies the amount of time to wait for a server's first response headers after fully writing the request headers. mandatory
tlsMinVersion tlsMinVersion specifies minimum TLS version enforced for http client. Valid values are 1.0, 1.1, 1.2, 1.3 optional
requestConfig := NewRequestConfig("test", nil).SetTimeout(1000).
		SetRetryCount(3).
		SetMethod("GET").SetURL("http://google.com")
Using config map

Applications can use yaml files to configure all the http configurations. Use https://github.com/sinhashubham95/go-config-client to read yaml and get map[string]interface{}

// config map - note that constant backoff is given more preference over exponential backoff if both are set
configMap := map[string]interface{}{
    "method":          "GET",
    "url":             "https://www.google.co.in",
    "timeoutinmillis": 5000,
    "retrycount":      3,
    "backoffpolicy": map[string]interface{}{
        "constantbackoff": map[string]interface{}{
            "intervalinmillis":          2,
            "maxjitterintervalinmillis": 5,
        },
        "exponentialbackoff": map[string]interface{}{
            "initialtimeoutinmillis":    2,
            "maxtimeoutinmillis":        10,
            "exponentfactor":            2.0,
            "maxjitterintervalinmillis": 2,
        },
    },
    "hystrixconfig": map[string]interface{}{
        "maxconcurrentrequests":  10,
        "errorpercentthreshold":  20,
        "sleepwindowinmillis":    10,
        "requestvolumethreshold": 10,
    },
}

//setup activity
requestConfig := NewRequestConfig("test", configMap)
Configure Client using NewRequestConfig

You can pass as many requestConfig

httpclient := ConfigureHTTPClient(*requestConfig)

This can also be used to reconfigure client for exist request.

Making a request
res, error := httpclient.Request(
		NewRequest("test"),
	)

NewRequest has following tunables

field/method description optional
request name A unique name must be passed as parameter mandatory
SetQueryParam set a query param optional
SetQueryParams set map query params optional
SetHeaderParams set headers optional
SetBody set request body optional
Yaml config

Keys must match NewRequestConfig struct

sample-call-1:
  method: "GET"
  url: "http://google.com"
  timeoutInMillis: 1000
  retryCount: 3
  backoffPolicy:
    constantBackoff:
      intervalInMillis: 2
      maxJitterIntervalInMillis: 5
    exponentialBackoff:
      initialTimeoutInMillis: 2
      maxTimeoutInMillis: 10
      exponentFactor: 2
      maxJitterIntervalInMillis: 2
  hystrixConfig:
    maxConcurrentRequests: 10
    errorPercentThresold: 20
    sleepWindowInMillis : 10
    requestVolumeThreshold: 10

sample-call-2:
  method: "GET"
  url: "http://google.com"
  timeoutInMillis: 1000
  retryCount: 3
  backoffPolicy:
    constantBackoff:
      intervalInMillis: 2
      maxJitterIntervalInMillis: 5
    exponentialBackoff:
      initialTimeoutInMillis: 2
      maxTimeoutInMillis: 10
      exponentFactor: 2
      maxJitterIntervalInMillis: 2
  hystrixConfig:
    maxConcurrentRequests: 10
    errorPercentThresold: 20
    sleepWindowInMillis : 10
    requestVolumeThreshold: 10

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BackoffPolicy

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

BackoffPolicy is the type for backoff policy

func NewBackoffPolicy

func NewBackoffPolicy(configMap map[string]interface{}) *BackoffPolicy

NewBackoffPolicy is used to create a new backoff policy

func (*BackoffPolicy) SetConstantBackoff

func (bop *BackoffPolicy) SetConstantBackoff(constantBackoff *ConstantBackoff) *BackoffPolicy

SetConstantBackoff is used to use the constant backoff policy

func (*BackoffPolicy) SetExponentialBackoff

func (bop *BackoffPolicy) SetExponentialBackoff(exponentialBackoff *ExponentialBackoff) *BackoffPolicy

SetExponentialBackoff is used to set the exponential backoff policy

type Client

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

Client is the http client

func ConfigureHTTPClient

func ConfigureHTTPClient(requestConfigs ...*RequestConfig) *Client

ConfigureHTTPClient receives RequestConfigs and initializes one http client per RequestConfig. It creates heimdall http or hystrix client based on the configuration provided in RequestConfig. Returns the instance of Client

func (*Client) Request

func (c *Client) Request(request *Request) (*http.Response, error)

Request receives Request param to execute. It will fetch the right http client for given Request name and use it to execute based on attributes provided in Request It returns http.Response and error

func (*Client) WithLogger

func (c *Client) WithLogger(l Logger) *Client

WithLogger is used to provide the logger instance for the http client created

func (*Client) WithMetrics

func (c *Client) WithMetrics(m Metrics) *Client

WithMetrics is used to provide the metrics instance for the http client created

type ClientRequestMapping

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

ClientRequestMapping provides a container for heimdall client and associated RequestConfig.

type ConstantBackoff

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

ConstantBackoff is used to create a new constant backoff

func NewConstantBackoff

func NewConstantBackoff(configMap map[string]interface{}) *ConstantBackoff

NewConstantBackoff is used to create a new constant backoff

func (*ConstantBackoff) SetInterval

func (cb *ConstantBackoff) SetInterval(interval time.Duration) *ConstantBackoff

SetInterval is used to set the interval for the backoff

func (*ConstantBackoff) SetMaximumJitterInterval

func (cb *ConstantBackoff) SetMaximumJitterInterval(maximumJitterInterval time.Duration) *ConstantBackoff

SetMaximumJitterInterval is used to set the jitter interval

type ExponentialBackoff

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

ExponentialBackoff is used to create a new exponential backoff

func NewExponentialBackoff

func NewExponentialBackoff(configMap map[string]interface{}) *ExponentialBackoff

NewExponentialBackoff is used to create a new exponential backoff

func (*ExponentialBackoff) SetExponentFactor

func (eb *ExponentialBackoff) SetExponentFactor(exponentFactor float64) *ExponentialBackoff

SetExponentFactor is used to set the exponential factor for backoff

func (*ExponentialBackoff) SetInitialTimeout

func (eb *ExponentialBackoff) SetInitialTimeout(initialTimeout time.Duration) *ExponentialBackoff

SetInitialTimeout is used to set the initial wait time before the backoff

func (*ExponentialBackoff) SetMaxTimeout

func (eb *ExponentialBackoff) SetMaxTimeout(maxTimeout time.Duration) *ExponentialBackoff

SetMaxTimeout is used to set the maximum timeout duration

func (*ExponentialBackoff) SetMaximumJitterInterval

func (eb *ExponentialBackoff) SetMaximumJitterInterval(maximumJitterInterval time.Duration) *ExponentialBackoff

SetMaximumJitterInterval is used to set the jitter interval

type HystrixConfig

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

HystrixConfig is the configuration for hystrix

func NewHystrixConfig

func NewHystrixConfig(configMap map[string]interface{}) *HystrixConfig

NewHystrixConfig is used to create a new configuration for hystrix

func (*HystrixConfig) SetErrorPercentThreshold

func (hc *HystrixConfig) SetErrorPercentThreshold(errorPercentThreshold int) *HystrixConfig

SetErrorPercentThreshold is used to set the error percent threshold in hystrix

func (*HystrixConfig) SetFallback

func (hc *HystrixConfig) SetFallback(fallbackFn func(error) error) *HystrixConfig

SetFallback is used to set the fallback

func (*HystrixConfig) SetHystrixTimeout

func (hc *HystrixConfig) SetHystrixTimeout(hystrixTimeout time.Duration) *HystrixConfig

SetHystrixTimeout is used to set the hystrix timeout

func (*HystrixConfig) SetMaxConcurrentRequests

func (hc *HystrixConfig) SetMaxConcurrentRequests(maxConcurrentRequests int) *HystrixConfig

SetMaxConcurrentRequests is used to set the max concurrent requests in hystrix

func (*HystrixConfig) SetRequestVolumeThreshold

func (hc *HystrixConfig) SetRequestVolumeThreshold(requestVolumeThreshold int) *HystrixConfig

SetRequestVolumeThreshold is used to set the request volume threshold

func (*HystrixConfig) SetSleepWindowInMillis

func (hc *HystrixConfig) SetSleepWindowInMillis(sleepWindowInMillis int) *HystrixConfig

SetSleepWindowInMillis is used to set the sleep window in hystrix

type Logger

type Logger func(ctx context.Context, msg string)

Logger is the logger used to log the http traces

type Metric

type Metric struct {
	Status          int   `json:"status"`
	LatencyInMillis int64 `json:"latency"`
}

Metric is the information used to tracking the performance

type Metrics

type Metrics func(ctx context.Context, name string, m Metric)

Metrics provides the basic information for status and latency

type Request

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

Request is the type for the request created

func NewRequest

func NewRequest(name string) *Request

NewRequest creates a Request to execute It takes request name as input. It must match with request name used to configure RequestConfig

func (*Request) SetBody

func (req *Request) SetBody(body io.Reader) *Request

SetBody is used to set request body to pass in http request

func (*Request) SetContext

func (req *Request) SetContext(ctx context.Context) *Request

SetContext is used to set the context for the request

func (*Request) SetHeaderParam

func (req *Request) SetHeaderParam(param, value string) *Request

SetHeaderParam is used to set a header - key-value pair These will be passed in header while executing HTTP request

func (*Request) SetHeaderParams

func (req *Request) SetHeaderParams(headerParams map[string]string) *Request

SetHeaderParams is used to set multiple headers - map of key-value pair These will be passed in header while executing HTTP request

func (*Request) SetMethod

func (req *Request) SetMethod(method string) *Request

SetMethod is used to set the method for the request

func (*Request) SetQueryParam

func (req *Request) SetQueryParam(param, value string) *Request

SetQueryParam is used to set a query param key value pair These will be passed in query param while executing HTTP request

func (*Request) SetQueryParams

func (req *Request) SetQueryParams(queryParams map[string]string) *Request

SetQueryParams is used to set multiple query params - map of key-value pair These will be passed in query param while executing HTTP request

func (*Request) SetURL

func (req *Request) SetURL(url string) *Request

SetURL is used to set the url for the request if not done, then the url already configured will be used

type RequestConfig

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

RequestConfig is the type for a request configuration

func NewRequestConfig

func NewRequestConfig(name string, configMap map[string]interface{}) *RequestConfig

NewRequestConfig is used to create a new request configuration from a map of configurations.

func (*RequestConfig) SetBackoffPolicy

func (rc *RequestConfig) SetBackoffPolicy(backoffPolicy *BackoffPolicy) *RequestConfig

SetBackoffPolicy is used to set the backoff policy for request

func (*RequestConfig) SetCheckRedirect

func (rc *RequestConfig) SetCheckRedirect(checkRedirect func(*http.Request, []*http.Request) error) *RequestConfig

SetCheckRedirect CheckRedirect specifies the policy for handling redirects.

func (*RequestConfig) SetConnectTimeout

func (rc *RequestConfig) SetConnectTimeout(connectTimeout time.Duration) *RequestConfig

SetConnectTimeout is used to set connect timeout

func (*RequestConfig) SetExpectContinueTimeout

func (rc *RequestConfig) SetExpectContinueTimeout(expectContinueTimeout time.Duration) *RequestConfig

SetExpectContinueTimeout is used to set expect continue timeout for request

func (*RequestConfig) SetHeaderParams

func (rc *RequestConfig) SetHeaderParams(headers map[string]interface{}) *RequestConfig

SetHeaders is used to set the headers. Setting the headers overrides the default header

func (*RequestConfig) SetHystrixConfig

func (rc *RequestConfig) SetHystrixConfig(hystrixConfig *HystrixConfig) *RequestConfig

SetHystrixConfig is used to set the hystrix config for the request

func (*RequestConfig) SetHystrixFallback

func (rc *RequestConfig) SetHystrixFallback(fallbackFn func(error) error) *RequestConfig

SetHystrixFallback is used to set the hystrix fallback for the request

func (*RequestConfig) SetIdleConnectionTimeout

func (rc *RequestConfig) SetIdleConnectionTimeout(idleConnectionTimeout time.Duration) *RequestConfig

SetIdleConnectionTimeout is used to set the idle connection timeout for request

func (*RequestConfig) SetKeepAlive

func (rc *RequestConfig) SetKeepAlive(keepalive time.Duration) *RequestConfig

SetKeepAlive is used to set the keep alive for request

func (*RequestConfig) SetMaxIdleConnections

func (rc *RequestConfig) SetMaxIdleConnections(maxIdleConnections int) *RequestConfig

SetMaxIdleConnections is used to set the max idle connections for request

func (*RequestConfig) SetMethod

func (rc *RequestConfig) SetMethod(method string) *RequestConfig

SetMethod is used to set method for request

func (*RequestConfig) SetName

func (rc *RequestConfig) SetName(name string) *RequestConfig

SetName is used to set name for request

func (*RequestConfig) SetProxy

func (rc *RequestConfig) SetProxy(proxyURL string) *RequestConfig

SetProxy is used to set the proxy url for request

func (*RequestConfig) SetRetryCount

func (rc *RequestConfig) SetRetryCount(retryCount int) *RequestConfig

SetRetryCount is used to set the retry count for request

func (*RequestConfig) SetTLSHandshakeTimeout

func (rc *RequestConfig) SetTLSHandshakeTimeout(tlsHandshakeTimeout time.Duration) *RequestConfig

SetTLSHandshakeTimeout is used to set the tls handshake timeout for request

func (*RequestConfig) SetTimeout

func (rc *RequestConfig) SetTimeout(timeout time.Duration) *RequestConfig

SetTimeout is used to set the timeout for request

func (*RequestConfig) SetTransport

func (rc *RequestConfig) SetTransport(transport http.RoundTripper) *RequestConfig

SetTransport is used to set the transport. Setting the transport overrides the default transport

func (*RequestConfig) SetURL

func (rc *RequestConfig) SetURL(url string) *RequestConfig

SetURL is used to set the url for request

func (*RequestConfig) Transport

func (rc *RequestConfig) Transport() http.RoundTripper

Transport is used to get the transport set for Request config.

Jump to

Keyboard shortcuts

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