Categorygithub.com/globocom/httpclient
modulepackage
0.0.0-20240418124943-c32f55890b08
Repository: https://github.com/globocom/httpclient.git
Documentation: pkg.go.dev

# 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
}

# Functions

No description provided by the author
NewHTTPClient instantiates a new HTTPClient.
WithAuthToken encapsulates the resty library to provide token authentication.
WithBackoff sets a retry strategy based on its configuration.
WithBasicAuth encapsulates the resty library to provide basic authentication.
WithChainCallback provides a callback functionality that takes as input a Callback type.
WithCircuitBreaker enables circuit breaker strategy based on circuitbreaker.Config.
WithCookie encapsulates the resty library to set a cookie to client instance.
WithDefaultTransport sets a custom connection timeout to http.Transport.
WithDefaultTransportWithProxy sets a custom url to use as a proxy to requests.
No description provided by the author
WithHostURL encapsulates the resty library to set a host url.
No description provided by the author
WithMetrics creates a layer to facilitate the metrics use.
WithOAUTHTransport allows the client to make OAuth HTTP requests with custom timeout.
WithProxy encapsulates the resty library to set a proxy URL and port.
WithRetries sets a retry strategy based on its configuration.
WithRetryConditions sets conditions to retry strategy.
WithTimeout encapsulates the resty library to set a custom request timeout.
WithTransport configures the client to use a custom *http.Transport More information about transport: [net/http.Transport].
WithUserAgent encapsulates the resty library to set a custom user agent to requests.

# Variables

No description provided by the author

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Transport accepts a custom RoundTripper and acts as a middleware to facilitate logging and argument passing to external requests.

# Interfaces

No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author