httpclient

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

httpclient

Go Reference

Cliente HTTP extensível para Go, com suporte a middlewares (logging, headers, cache, circuit breaker), base URL, timeout e métodos HTTP completos.

Instalação

go get gitlab.globoi.com/globoplay/go-prime/clients/httpclient

Visão Geral

  • Base URL e timeout configuráveis
  • Headers globais
  • Middlewares plugáveis
  • Métodos HTTP: GET, POST, PUT, PATCH, DELETE, HEAD

Exemplo Rápido

import (
    "context"
    "time"
    "gitlab.globoi.com/globoplay/go-prime/clients/httpclient"
)

client := httpclient.NewHTTPClient(
    "https://api.example.com",
    5*time.Second,
)

resp, err := client.Get(context.Background(), "/users/1")

Middlewares

O httpclient suporta middlewares para customizar o comportamento das requisições. Você pode combiná-los conforme a necessidade do seu projeto.

Logging Middleware

Registra todas as requisições e respostas, incluindo método, URL, status, duração e cache. Útil para auditoria e troubleshooting.

Configuração:

client := httpclient.NewHTTPClient(
    baseURL,
    5*time.Second,
    httpclient.NewLoggingMiddleware("my-service"),
)
Header Middleware

Adiciona ou sobrescreve headers em todas as requisições. Ideal para autenticação, rastreamento e customização de chamadas.

Configuração:

client := httpclient.NewHTTPClient(
    baseURL,
    5*time.Second,
    httpclient.NewHeaderMiddleware(map[string]string{
        "Authorization": "Bearer token",
        "X-Request-ID": "123",
    }),
)
Cache Middleware

Cacheia respostas de GET usando Redis. Reduz latência e carga em serviços externos.

Configuração:

import "gitlab.globoi.com/globoplay/go-prime/clients/redisclient"
redis := redisclient.NewRedisClient()
cfg := &httpclient.CacheConfig{
    RedisClient: redis,
    TTL:         30 * time.Second,
    OverrideTTL: true,
    Headers:     []string{"Authorization"},
}
client := httpclient.NewHTTPClient(baseURL, 5*time.Second, httpclient.CacheMiddleware(cfg))
Circuit Breaker Middleware

Protege contra falhas em serviços externos, abrindo o circuito após muitos erros. Evita sobrecarga e melhora a resiliência.

Configuração:

client := httpclient.NewHTTPClient(
    baseURL,
    5*time.Second,
    httpclient.NewCircuitBreakerMiddleware("my-service"),
)
Ordem recomendada dos middlewares
  1. Logging
  2. Headers
  3. Cache
  4. Circuit Breaker
client := httpclient.NewHTTPClient(
    baseURL,
    5*time.Second,
    httpclient.NewLoggingMiddleware("my-service"),
    httpclient.NewHeaderMiddleware(map[string]string{"Authorization": "Bearer token"}),
    httpclient.CacheMiddleware(cfg),
    httpclient.NewCircuitBreakerMiddleware("my-service"),
)

Métodos Disponíveis

Método Descrição
Get Requisição GET
Post Requisição POST com body
Put Requisição PUT com body
Patch Requisição PATCH com body
Delete Requisição DELETE
Head Requisição HEAD

Todos os métodos recebem context.Context e retornam *HTTPResponse e error.

Exemplos de Uso

import (
    "context"
    "strings"
    "log"
)

ctx := context.Background()

// GET
resp, err := client.Get(ctx, "/users/1")
if err != nil { log.Fatal(err) }
log.Println("GET:", resp.StatusCode, resp.Body)

// POST
body := strings.NewReader(`{"name":"Luiz"}`)
resp, err = client.Post(ctx, "/users", body)
if err != nil { log.Fatal(err) }
log.Println("POST:", resp.StatusCode, resp.Body)

// PUT
body = strings.NewReader(`{"name":"Novo Nome"}`)
resp, err = client.Put(ctx, "/users/1", body)
if err != nil { log.Fatal(err) }
log.Println("PUT:", resp.StatusCode, resp.Body)

// PATCH
body = strings.NewReader(`{"name":"Parcial"}`)
resp, err = client.Patch(ctx, "/users/1", body)
if err != nil { log.Fatal(err) }
log.Println("PATCH:", resp.StatusCode, resp.Body)

// DELETE
resp, err = client.Delete(ctx, "/users/1")
if err != nil { log.Fatal(err) }
log.Println("DELETE:", resp.StatusCode)

// HEAD
resp, err = client.Head(ctx, "/users/1")
if err != nil { log.Fatal(err) }
log.Println("HEAD:", resp.StatusCode)

Sequência de execução dos middlewares

  1. Logging Middleware
  2. Header Middleware
  3. Cache Middleware
  4. Circuit Breaker Middleware

API

Veja a documentação completa em pkg.go.dev.

Contribuindo

Contribuições são bem-vindas! Abra issues ou pull requests.

Licença

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CacheMiddleware

func CacheMiddleware(cfg *CacheConfig) func(next http.RoundTripper) http.RoundTripper

CacheMiddleware is an HTTP middleware that provides transparent caching for GET requests using a Redis backend.

It checks if the cache is enabled and a Redis client is configured. For each GET request, it attempts to retrieve a cached response from Redis using a generated cache key. If a valid cached response is found, it is deserialized and returned immediately, setting the "X-Cache" header to "HIT". If not found, the request proceeds to the next RoundTripper, and the response is cached asynchronously if the status code is 2xx. The cache TTL can be overridden by configuration, and the middleware also updates the "Cache-Control" header accordingly.

Parameters:

cfg *CacheConfig: Cache configuration struct.
  - RedisClient: Redis client used to store and retrieve cached data.
  - TTL: Default expiration time (Time To Live) for cache entries.
  - OverrideTTL: If true, overrides the TTL from the Cache-Control header with the configured TTL.
  - Headers: HTTP headers that will be considered when generating the cache key.

Returns:

A function that wraps an http.RoundTripper with caching logic.

func NewCircuitBreakerMiddleware

func NewCircuitBreakerMiddleware(name string) func(next http.RoundTripper) http.RoundTripper

NewCircuitBreaker wraps an http.RoundTripper with a circuit breaker using gobreaker.

The circuit breaker monitors HTTP requests and opens the circuit when the error rate reaches a threshold (default: 50% errors out of at least 20 requests, considering status >= 500 or 429 as errors). While open, requests will fail fast without calling the underlying transport. After a short interval, a limited number of requests are allowed to test recovery. If successful, the circuit closes again.

Parameters:

cfg: Configuration for the circuit breaker.
     - cfg.Enabled: activates/deactivates the breaker.
     - cfg.Name: identifies the breaker instance (useful for logging/metrics).
next: The next http.RoundTripper to be wrapped. This is usually http.DefaultTransport or a custom transport.

Returns:

An http.RoundTripper that applies circuit breaker logic to all requests.

func NewHeaderMiddleware

func NewHeaderMiddleware(headers map[string]string) func(next http.RoundTripper) http.RoundTripper

NewHeaderMiddleware returns an HTTP middleware that adds custom headers to all outgoing requests.

Parameters:

headers: A map of header keys and values to be set on each outgoing HTTP request.

Returns:

A function that wraps an http.RoundTripper and sets the provided headers on every request before forwarding it.
Existing headers with the same key will be overwritten.

func NewLoggingMiddleware

func NewLoggingMiddleware(name string) func(next http.RoundTripper) http.RoundTripper

Types

type CacheConfig

type CacheConfig struct {
	RedisClient IRedisClient
	TTL         time.Duration
	OverrideTTL bool
	Headers     cacheKeyHeaders
}

CacheConfig holds the configuration for the cache middleware, including Redis client, TTL, and headers for cache key.

type CachePolicy

type CachePolicy struct {
	MaxAge  int      `json:"maxAge"`
	Headers []string `json:"headers"`
}

CachePolicy defines cache control policy for a cached response, including max-age and headers used.

type HTTPClient

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

func NewHTTPClient

func NewHTTPClient(
	baseUrl string,
	timeout time.Duration,
	middlewares ...RoundTripperMiddleware) *HTTPClient

NewHTTPClient creates a new HTTPClient instance.

Params:

  • baseUrl: Base URL for requests (used if path is relative).

  • timeout: Timeout for HTTP requests.

  • middlewares: Optional RoundTripper middlewares.

    Recommended order:

    1. NewLoggingMiddleware; (Should be outermost to log all requests and responses, including cache hits and circuit breaker events)

    2. NewHeaderMiddleware; (Sets custom headers before cache and circuit logic, ensuring cache keys and backend requests use the correct headers)

    3. CacheMiddleware; (Checks/sets cache after headers are set, and before circuit breaker, for maximum cache efficiency)

    4. CircuitBreakerMiddleware. (Protects backend only for requests that reach it, after cache and header logic)

Returns: Configured HTTP client.

func (*HTTPClient) Delete

func (c *HTTPClient) Delete(ctx context.Context, path string) (*HTTPResponse, error)

Delete sends an HTTP DELETE request to the specified path.

Parameters:

  • ctx: Context for cancellation and timeout.
  • path: Request path or full URL.

Returns:

  • *HTTPResponse: The response object.
  • error: Any error encountered.

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, path string) (*HTTPResponse, error)

Get sends an HTTP GET request to the specified path.

Parameters:

  • ctx: Context for cancellation and timeout.
  • path: Request path or full URL.

Returns:

  • *HTTPResponse: The response object.
  • error: Any error encountered.

func (*HTTPClient) Head

func (c *HTTPClient) Head(ctx context.Context, path string) (*HTTPResponse, error)

Head sends an HTTP HEAD request to the specified path.

Parameters:

  • ctx: Context for cancellation and timeout.
  • path: Request path or full URL.

Returns:

  • *HTTPResponse: The response object.
  • error: Any error encountered.

func (*HTTPClient) Patch

func (c *HTTPClient) Patch(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)

Patch sends an HTTP PATCH request to the specified path with a request body.

Parameters:

  • ctx: Context for cancellation and timeout.
  • path: Request path or full URL.
  • body: Request body as io.Reader.

Returns:

  • *HTTPResponse: The response object.
  • error: Any error encountered.

func (*HTTPClient) Post

func (c *HTTPClient) Post(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)

Post sends an HTTP POST request to the specified path with a request body.

Parameters:

  • ctx: Context for cancellation and timeout.
  • path: Request path or full URL.
  • body: Request body as io.Reader.

Returns:

  • *HTTPResponse: The response object.
  • error: Any error encountered.

func (*HTTPClient) Put

func (c *HTTPClient) Put(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)

Put sends an HTTP PUT request to the specified path with a request body.

Parameters:

  • ctx: Context for cancellation and timeout.
  • path: Request path or full URL.
  • body: Request body as io.Reader.

Returns:

  • *HTTPResponse: The response object.
  • error: Any error encountered.

type HTTPResponse

type HTTPResponse struct {
	Body       any
	StatusCode int
	Headers    http.Header
}

type HTTPStatusError

type HTTPStatusError struct {
	Status int
	Err    error
}

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

type IRedisClient

type IRedisClient interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key string, value any, expiration time.Duration) error
}

IRedisClient defines the interface for a Redis client used by the cache middleware. It must implement Get and Set methods for string keys and values.

type RoundTripperFunc

type RoundTripperFunc func(*http.Request) (*http.Response, error)

RoundTripperFunc allows using ordinary functions as http.RoundTripper implementations.

func (RoundTripperFunc) RoundTrip

func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip calls the underlying function, allowing RoundTripperFunc to satisfy http.RoundTripper.

type RoundTripperMiddleware

type RoundTripperMiddleware func(http.RoundTripper) http.RoundTripper

RoundTripperMiddleware defines a function that wraps an http.RoundTripper with additional behavior (middleware).

type SerializableCache

type SerializableCache struct {
	Status            string              `json:"status"`
	StatusCode        int                 `json:"status_code"`
	Proto             string              `json:"proto"`
	ResponseHeaders   map[string][]string `json:"header"`
	Body              string              `json:"body"`
	CacheControlValue int                 `json:"cacheControlValue"`
	Policy            CachePolicy         `json:"policy"`
}

SerializableCache represents the structure of a cached HTTP response, ready for (de)serialization.

Jump to

Keyboard shortcuts

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