httpclient

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2023 License: MIT Imports: 5 Imported by: 0

README

http-client

Simple golang package with fasthttp client and prometheus metric.

Example NewWithMetric

// metric
var netSourcesLatencyHistogram = func() *prometheus.HistogramVec {
    var metric = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Namespace: "service",
            Subsystem: "net",
            Name:      "sources_latency",
            Help:      "Third party response latency histogram.",
            Buckets:   prometheus.ExponentialBuckets(0.05, 2, 8),
        }, []string{"source"})
    prometheus.MustRegister(metric)

    return metric
}()

// create
client := httpclient.NewWithMetric("domain", netSourcesLatencyHistogram)

// request
if err := p.client.DoTimeout(req, resp); err != nil {
    // error handling
}

Example NewWithMetricFunc

// metric func
var latencyFunc = func(start time.Time, domain string) {
    latencyMetric.WithLabelValues(domain).Observe(float64(time.Since(start).Nanoseconds()) / 1000000)
}

// func
client := httpclient.NewWithMetricFunc("domain", latencyFunc)

// request
if err := p.client.DoTimeout(req, resp); err != nil {
    // error handling
}

Documentation

Overview

Package httpclient provides easy way to crate http client with retry and timeout.

Index

Constants

View Source
const (
	// DefaultRetry - количество ретраев под текущую реализацию переключения между основными api и failover.
	DefaultRetry = 2
	// DefaultTimeout - стандартное время ожидания ответа от сервера.
	DefaultTimeout = 3 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Backoff

type Backoff struct {
	Min       time.Duration
	Max       time.Duration
	Calculate func(int) time.Duration
}

Backoff - provide essention backoff parameters.

func NewBackoff

func NewBackoff(min, max time.Duration) *Backoff

NewBackoff - return function for new backoff calculation.

type Client

type Client struct {
	RetryMax int              // Количество попыток запроса.
	Timeout  time.Duration    // Таймаут для http запроса.
	Backoff  *Backoff         // Рассчёт времени ожидания между попытками запроса.
	HTTP     *fasthttp.Client // HTTP клиент.
	// contains filtered or unexported fields
}

Client is a convenient API to make HTTP calls. Client also handles automatically retrying failed HTTP requests.

func New

func New(retry int, timeout time.Duration) Client

New - return new http client with given params & backoff.

func NewDefault

func NewDefault() Client

NewDefault - return new http client with default params & backoff.

func NewWithMetric

func NewWithMetric(domain string, latencyMetric *prometheus.HistogramVec) Client

NewWithMetric - return new http client with default params & backoff.

func NewWithMetricFunc added in v1.4.0

func NewWithMetricFunc(domain string, latencyFunc func(start time.Time, domain string)) Client

NewWithMetricFunc - return new http client with default params & backoff.

func (*Client) CheckRetry added in v1.2.1

func (c *Client) CheckRetry(try int) bool

CheckRetry will return a boolean value depending on whether the attempts ended or not.

func (*Client) CheckRetryWithBackoff added in v1.2.1

func (c *Client) CheckRetryWithBackoff(try int) bool

CheckRetryWithBackoff will return a boolean value depending on whether the attempts ended or not. If the attempts are over - the value will be returned immediately, if not - the value will be returned after the waiting time set via the backoff function.

func (*Client) Do added in v1.1.3

func (c *Client) Do(req *fasthttp.Request, resp *fasthttp.Response) error

Do performs the given http request and fills the given http response.

func (*Client) DoContext added in v1.2.0

func (c *Client) DoContext(ctx context.Context, req *fasthttp.Request, resp *fasthttp.Response) error

DoContext perform the given request with ctx deadline or waits for response during the given timeout duration.

func (*Client) DoTimeout

func (c *Client) DoTimeout(req *fasthttp.Request, resp *fasthttp.Response) error

DoTimeout performs the given request and waits for response during the given timeout duration.

func (*Client) SetTimeout added in v1.1.3

func (c *Client) SetTimeout(timeout time.Duration)

Jump to

Keyboard shortcuts

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