httpclient

package
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

HTTPClient Module

The httpclient module provides an enterprise-grade, resilient wrapper around the popular go-resty/resty HTTP client. It is designed specifically for Microservices architectures, protecting your services from cascading failures when calling unreliable third-party APIs.

Features

  1. Auto-Retry with Backoff: Automatically retries failed requests (network errors or 5xx status codes) with Exponential Backoff.
  2. Circuit Breaker: Integrates sony/gobreaker. If an external service is down and continuously returning errors, the Circuit Breaker will "trip" (Open State), failing fast for subsequent requests to prevent resource exhaustion (goroutine leaks, high memory usage) while the external service recovers.
  3. OpenTelemetry Tracing: Automatically injects W3C Trace Context into outbound HTTP headers (traceparent), allowing you to trace requests seamlessly across microservice boundaries.
  4. Fluent API: Retains the elegant, chainable API of go-resty.

Installation

go get github.com/thanhbvha/go-common/httpclient

Basic Usage

package main

import (
	"context"
	"fmt"
	"github.com/go-resty/resty/v2"
	"github.com/thanhbvha/go-common/httpclient"
)

func main() {
	// 1. Initialize Default Config
	// This enables Retry (3 attempts) and Circuit Breaker by default.
	cfg := httpclient.DefaultConfig("https://api.github.com")
	
	// 2. Create the resilient client
	client := httpclient.NewClient(cfg)

	// 3. Execute request safely
	resp, err := client.Execute(context.Background(), func(req *resty.Request) (*resty.Response, error) {
		return req.
			SetHeader("Accept", "application/json").
			Get("/users/octocat")
	})

	if err != nil {
		// If the external service is down, the Circuit Breaker might return an OpenState error
		// instead of blocking your thread waiting for a timeout.
		fmt.Printf("Request failed: %v\n", err)
		return
	}

	fmt.Printf("Status: %d\n", resp.StatusCode())
}

Configuration Options

You can deeply customize the retry and circuit breaker logic:

cfg := httpclient.Config{
	BaseURL: "https://flaky-api.com",
	Timeout: 5 * time.Second,
	Retry: httpclient.RetryConfig{
		Enabled:     true,
		MaxRetries:  5,
		WaitTime:    1 * time.Second,
		MaxWaitTime: 10 * time.Second,
	},
	CircuitBreaker: httpclient.CBConfig{
		Enabled:                true,
		Name:                   "flaky-api-cb",
		Timeout:                30 * time.Second, // Stay Open for 30s before testing Half-Open
		ReadyToTripMinRequests: 10,               // Need at least 10 requests to evaluate
		ReadyToTripFailRatio:   0.5,              // Trip if 50% of requests fail
	},
}

Documentation

Overview

Package httpclient provides a resilient HTTP client wrapper around go-resty. It features automatic Retries with exponential backoff, Circuit Breaker via gobreaker, and automatic OpenTelemetry W3C Trace Context propagation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CBConfig

type CBConfig struct {
	Enabled                bool
	Name                   string
	MaxRequests            uint32
	Interval               time.Duration
	Timeout                time.Duration
	ReadyToTripFailRatio   float64
	ReadyToTripMinRequests uint32
	OnStateChange          func(name string, from gobreaker.State, to gobreaker.State)
}

CBConfig configures the Circuit Breaker pattern.

type Client

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

Client is a wrapper around resty.Client that provides Circuit Breaking and Telemetry.

func NewClient

func NewClient(cfg Config) *Client

NewClient creates a new resilient HTTP Client.

func (*Client) Execute

func (c *Client) Execute(ctx context.Context, fn func(req *resty.Request) (*resty.Response, error)) (*resty.Response, error)

Execute performs an HTTP request wrapped in a Circuit Breaker (if enabled). The provided function `fn` describes how to actually build and send the request using the Resty client.

func (*Client) Native

func (c *Client) Native() *resty.Client

Native returns the underlying resty.Client in case advanced configuration is needed.

type Config

type Config struct {
	BaseURL         string
	Timeout         time.Duration
	Retry           RetryConfig
	CircuitBreaker  CBConfig
	EnableTelemetry bool
}

Config represents the overall configuration for the HTTP Client.

func DefaultConfig

func DefaultConfig(baseURL string) Config

DefaultConfig returns a recommended set of default configurations.

type RetryConfig

type RetryConfig struct {
	Enabled     bool
	MaxRetries  int
	WaitTime    time.Duration
	MaxWaitTime time.Duration
}

RetryConfig configures the auto-retry mechanism.

Jump to

Keyboard shortcuts

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