httpclient

package module
v0.0.0-...-c32f558 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: BSD-3-Clause Imports: 17 Imported by: 0

README

httpclient

A HTTP client implementation in GoLang.

Examples

1. OAuth Authorization
package example

import (
	"context"
	"log"
	"time"

	"github.com/globocom/httpclient"
	"golang.org/x/oauth2/clientcredentials"
)

func main() {
    timeout := 200 * time.Millisecond
    contextTimeout, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()

    credentials := clientcredentials.Config{
        ClientID:     "client_id",
        ClientSecret: "client_secret",
        TokenURL:     "client_url/token",
        Scopes:       []string{"grant_permissions:client_credentials"},
    }

    client := httpclient.NewHTTPClient(httpclient.LoggerAdapter{Writer: log.Writer()},
        httpclient.WithOAUTHTransport(credentials, timeout))

    resp, err := client.NewRequest().
        SetContext(contextTimeout).
        Put("/authorize")

    log.Printf("resp: %#v", resp)
    log.Printf("err: %s", err)
}
2. Circuit Breaker with Timeout and Retries
package example

import (
	"log"
	"time"

	"github.com/slok/goresilience/circuitbreaker"
	"github.com/globocom/httpclient"
)
func main() {
    cbConfig := circuitbreaker.Config {
        ErrorPercentThresholdToOpen:        5,
        MinimumRequestToOpen:               50,
        SuccessfulRequiredOnHalfOpen:       50,
        WaitDurationInOpenState:            30 * time.Second,
        MetricsSlidingWindowBucketQuantity: 5,
        MetricsBucketDuration:              5 * time.Second,
    }

    timeout := 200 * time.Millisecond
    retries := 1
    backoff := 5 * time.Millisecond
    maxBackoff := 10 * time.Millisecond

    client := httpclient.NewHTTPClient(httpclient.LoggerAdapter{Writer: log.Writer()},
        httpclient.WithDefaultTransport(timeout),
        httpclient.WithTimeout(timeout),
        httpclient.WithCircuitBreaker(cbConfig),
        httpclient.WithRetries(retries, backoff, maxBackoff),
    )

    resp, err := client.NewRequest().
        Get("/example")

    log.Printf("resp: %#v", resp)
    log.Printf("err: %s", err)
}
3. Callback Chain
package example

import (
	"log"

	"github.com/globocom/httpclient"
)

func main() {
    client := httpclient.NewHTTPClient(
        httpclient.LoggerAdapter{Writer: log.Writer()},
        httpclient.WithChainCallback(loggerCallback),
    )
    resp, err := client.NewRequest().Get("example.com")
    log.Printf("resp: %#v", resp)
    log.Printf("err: %s", err)
}

func loggerCallback(fn func() (*httpclient.Response, error)) (*httpclient.Response, error) {
    resp, err := fn()

if resp != nil {
    restyRequest := resp.Request().RestyRequest()
    requestURL := restyRequest.RawRequest.URL
    host := requestURL.Host
    // If the client is initialized without WithHostURL, request.HostURL() is going to be nil
    if requestHostURL := resp.Request().HostURL(); requestHostURL != nil {
        host = requestHostURL.Host
    }

    responseTime := resp.ResponseTime().Microseconds()
    log.Printf("%s [%s] %d -- %s (%dμs)", host, restyRequest.Method,
        resp.StatusCode(), requestURL.String(), responseTime)
}

    return resp, err
}

Documentation

Index

Constants

This section is empty.

Variables

Functions

func NewDefaultTransport

func NewDefaultTransport(transportTimeout time.Duration) http.RoundTripper

func WithAuthToken

func WithAuthToken(token string) func(*HTTPClient)

WithAuthToken encapsulates the resty library to provide token authentication.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

func WithBackoff

func WithBackoff(retries int, waitTime time.Duration, exponential bool) func(*HTTPClient)

WithBackoff sets a retry strategy based on its configuration. This functionality relies on:

https://github.com/slok/goresilience/tree/master/circuitbreaker
https://github.com/go-resty/resty/tree/v1.x

Parameters:

retries: is used to set the number of retries after an error occurred.
waitTime: is the amount of time to wait for a new retry.
exponential: this field is used to specify which kind of backoff is used.

func WithBasicAuth

func WithBasicAuth(username, password string) func(*HTTPClient)

WithBasicAuth encapsulates the resty library to provide basic authentication.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

func WithChainCallback

func WithChainCallback(fn Callback) func(*HTTPClient)

WithChainCallback provides a callback functionality that takes as input a Callback type.

func WithCircuitBreaker

func WithCircuitBreaker(config circuitbreaker.Config) func(*HTTPClient)

WithCircuitBreaker enables circuit breaker strategy based on circuitbreaker.Config. This functionality relies on https://github.com/slok/goresilience/tree/master/circuitbreaker library.

The config fields are:
    ErrorPercentThresholdToOpen        int
    MinimumRequestToOpen               int
    SuccessfulRequiredOnHalfOpen       int
    WaitDurationInOpenState            time.Duration
    MetricsSlidingWindowBucketQuantity int
    MetricsBucketDuration              time.Duration

More information about circuitbreaker config: circuitbreaker.Config

func WithCookie

func WithCookie(name, value string) func(*HTTPClient)

WithCookie encapsulates the resty library to set a cookie to client instance.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

func WithDefaultTransport

func WithDefaultTransport(transportTimeout time.Duration) func(*HTTPClient)

WithDefaultTransport sets a custom connection timeout to http.Transport. This timeout limits the time spent establishing a TCP connection.

More information about timeout: net.Dialer.

func WithDefaultTransportWithProxy

func WithDefaultTransportWithProxy(proxyURL *url.URL) func(*HTTPClient)

WithDefaultTransportWithProxy sets a custom url to use as a proxy to requests. The proxyURL is used in the Proxy field. This field specifies a function to return a proxy for a given request.

More information about proxy: http.Transport.

func WithExponentialBackoff

func WithExponentialBackoff(retries int, waitTime time.Duration) func(*HTTPClient)

func WithHostURL

func WithHostURL(baseURL string) func(*HTTPClient)

WithHostURL encapsulates the resty library to set a host url.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

func WithLinearBackoff

func WithLinearBackoff(retries int, waitTime time.Duration) func(*HTTPClient)

func WithMetrics

func WithMetrics(m Metrics) func(*HTTPClient)

WithMetrics creates a layer to facilitate the metrics use.

Metrics interface implements
    IncrCounter(name string)
    PushToSeries(name string, value float64)

func WithOAUTHTransport

func WithOAUTHTransport(conf cc.Config, transportTimeout time.Duration) func(*HTTPClient)

WithOAUTHTransport allows the client to make OAuth HTTP requests with custom timeout. This timeout limits the time spent establishing a TCP connection.

The oauth2.Transport adds an Authorization header with a token using clientcredentials.Config information.

More information about timeout: net.Dialer.

More information about the fields used to create the token: clientcredentials.Config.

func WithProxy

func WithProxy(proxyAddress string) func(*HTTPClient)

WithProxy encapsulates the resty library to set a proxy URL and port.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

func WithRetries

func WithRetries(retries int, waitTime time.Duration, maxWaitTime time.Duration) func(*HTTPClient)

WithRetries sets a retry strategy based on its configuration. This functionality relies on:

https://github.com/go-resty/resty/tree/v1.x

Parameters:

retries: is used to set the number of retries after an error occurred.
waitTime: is the amount of time to wait for a new retry.
maxWaitTime: is the MAX amount of time to wait for a new retry.

func WithRetryConditions

func WithRetryConditions(conditions ...resty.RetryConditionFunc) func(*HTTPClient)

WithRetryConditions sets conditions to retry strategy. The conditions will be checked for a new retry. This functionality relies on:

https://github.com/go-resty/resty/tree/v1.x

More information about conditions: resty.RetryConditionFunc

func WithTimeout

func WithTimeout(timeout time.Duration) func(*HTTPClient)

WithTimeout encapsulates the resty library to set a custom request timeout.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

func WithTransport

func WithTransport(transport *http.Transport) func(*HTTPClient)

WithTransport configures the client to use a custom *http.Transport More information about transport: net/http.Transport

func WithUserAgent

func WithUserAgent(userAgent string) func(*HTTPClient)

WithUserAgent encapsulates the resty library to set a custom user agent to requests.

More information about this feature: https://github.com/go-resty/resty/tree/v1.x

Types

type Callback

type Callback func(func() (*Response, error)) (*Response, error)

type HTTPClient

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

func NewHTTPClient

func NewHTTPClient(logger resty.Logger, options ...Opt) *HTTPClient

NewHTTPClient instantiates a new HTTPClient.

Parameters:

logger: interface is used to log request and response details.
options: specifies options to HTTPClient.

func (*HTTPClient) GetClient

func (c *HTTPClient) GetClient() *http.Client

GetClient returns the current http.Client.

func (*HTTPClient) NewRequest

func (c *HTTPClient) NewRequest() *Request

NewRequest creates a request for the specified HTTP method.

type LoggerAdapter

type LoggerAdapter struct {
	Writer io.Writer
}

func (*LoggerAdapter) Debugf

func (l *LoggerAdapter) Debugf(format string, v ...interface{})

func (*LoggerAdapter) Errorf

func (l *LoggerAdapter) Errorf(format string, v ...interface{})

func (*LoggerAdapter) Infof

func (l *LoggerAdapter) Infof(format string, v ...interface{})

func (*LoggerAdapter) Warnf

func (l *LoggerAdapter) Warnf(format string, v ...interface{})

type Metrics

type Metrics interface {
	// IncrCounter increments the counter value identified by the given name.
	IncrCounter(name string)
	// PushToSeries adds a new value to a histogram identified by the given name.
	PushToSeries(name string, value float64)
	// IncrCounterWithAttrs increments the counter value identified by the given name while adding attributes.
	IncrCounterWithAttrs(name string, attributes map[string]string)
}

type Opt

type Opt func(*HTTPClient)

type Request

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

func (*Request) Delete

func (r *Request) Delete(url string) (*Response, error)

Delete performs an HTTP method DELETE request given an url.

func (*Request) Execute

func (r *Request) Execute(method string, url string) (*Response, error)

Execute performs the HTTP request with given HTTP method and URL. It also registers metrics, metrics fields are: host/alias occurrences, response time, response status code, quantity of occurrence of a circuit breaker open and errors occurred.

func (*Request) Get

func (r *Request) Get(url string) (*Response, error)

Get performs an HTTP method GET request given an url.

func (*Request) HostURL

func (r *Request) HostURL() *url.URL

HostURL returns the setted host url.

func (*Request) Post

func (r *Request) Post(url string) (*Response, error)

Post performs an HTTP method POST request given an url.

func (*Request) Put

func (r *Request) Put(url string) (*Response, error)

Put performs an HTTP method PUT request given an url.

func (*Request) RestyRequest

func (r *Request) RestyRequest() *resty.Request

RestyRequest RestyRequest gives access to the underlying *resty.Request.

func (*Request) SetAlias

func (r *Request) SetAlias(alias string) *Request

SetAlias sets the alias to replace the hostname in metrics.

func (*Request) SetAuthToken

func (r *Request) SetAuthToken(bearer string) *Request

SetAuthToken sets the bearer authentication header for the request.

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth sets the basic authentication header for the request.

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody sets the body for the request.

func (*Request) SetContext

func (r *Request) SetContext(context context.Context) *Request

SetContext sets the context for the request.

func (*Request) SetHeader

func (r *Request) SetHeader(name, value string) *Request

SetHeader sets the header for the request.

func (*Request) SetPathParams

func (r *Request) SetPathParams(params map[string]string) *Request

SetPathParams sets multiple key-value pairs to form the path for the request.

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams sets parameters to form a query string for the request.

type Response

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

func (Response) Body

func (r Response) Body() []byte

Body returns the response body.

func (Response) Cookie

func (r Response) Cookie(name string) *http.Cookie

Cookie finds a cookie by a name and returns it.

func (Response) Cookies

func (r Response) Cookies() []*http.Cookie

Cookies returns the response cookies.

func (Response) Header

func (r Response) Header() http.Header

Header returns the response header.

func (Response) Request

func (r Response) Request() *Request

Request returns the received request.

func (Response) ResponseTime

func (r Response) ResponseTime() time.Duration

ResponseTime returns the request response time.

func (Response) StatusCode

func (r Response) StatusCode() int

StatusCode returns the response status code.

type Transport

type Transport struct {
	RoundTripper http.RoundTripper
}

Transport accepts a custom RoundTripper and acts as a middleware to facilitate logging and argument passing to external requests.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip acts as a middleware performing external requests logging and argument passing to external requests.

Jump to

Keyboard shortcuts

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