httpclient

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package httpclient provides a production-ready HTTP client with automatic retries, exponential backoff, circuit breaker, and structured logging via slog.

Use the HTTPClient interface to accept either a real Client or a MockClient in your code, making external HTTP calls easy to test.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern

func NewCircuitBreaker

func NewCircuitBreaker(threshold int, timeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) Call

func (cb *CircuitBreaker) Call(fn func() error) error

Call executes the function if circuit is closed

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns current circuit state

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker

const (
	StateClosed CircuitState = iota
	StateOpen
	StateHalfOpen
)

Circuit breaker states.

type Client

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

Client is an HTTP client with retries, circuit breaker, and structured logging.

func New

func New(baseURL string, opts ...Option) *Client

New creates a new HTTP client with the given base URL and options.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string) (*Response, error)

Delete performs a DELETE request.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string) (*Response, error)

Get performs a GET request.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, body any) (*Response, error)

Patch performs a PATCH request with JSON body.

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body any) (*Response, error)

Post performs a POST request with JSON body.

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body any) (*Response, error)

Put performs a PUT request with JSON body.

func (*Client) Request

func (c *Client) Request() *RequestBuilder

Request creates a new request builder.

func (*Client) SetBearerToken

func (c *Client) SetBearerToken(token string) *Client

SetBearerToken sets Authorization header with Bearer token.

func (*Client) SetHeader

func (c *Client) SetHeader(key, value string) *Client

SetHeader sets a default header for all requests.

func (*Client) SetHeaders

func (c *Client) SetHeaders(headers map[string]string) *Client

SetHeaders sets multiple default headers.

type HTTPClient

type HTTPClient interface {
	Get(ctx context.Context, path string) (*Response, error)
	Post(ctx context.Context, path string, body any) (*Response, error)
	Put(ctx context.Context, path string, body any) (*Response, error)
	Patch(ctx context.Context, path string, body any) (*Response, error)
	Delete(ctx context.Context, path string) (*Response, error)
}

HTTPClient is the interface implemented by Client and MockClient.

type HTTPError

type HTTPError struct {
	StatusCode int
	Status     string
	Body       []byte
}

HTTPError represents an HTTP error response

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements error interface

func (*HTTPError) IsClientError

func (e *HTTPError) IsClientError() bool

IsClientError returns true if status is 4xx

func (*HTTPError) IsServerError

func (e *HTTPError) IsServerError() bool

IsServerError returns true if status is 5xx

type MockCall

type MockCall struct {
	Method string
	Path   string
	Body   any
	Time   time.Time
}

MockCall represents a recorded API call.

type MockClient

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

MockClient is a concurrency-safe mock HTTP client for testing.

func NewMockClient

func NewMockClient() *MockClient

NewMockClient creates a new mock client.

func (*MockClient) Delete

func (mc *MockClient) Delete(ctx context.Context, path string) (*Response, error)

Delete mocks DELETE request.

func (*MockClient) Get

func (mc *MockClient) Get(ctx context.Context, path string) (*Response, error)

Get mocks GET request.

func (*MockClient) GetCallCount

func (mc *MockClient) GetCallCount() int

GetCallCount returns the number of calls.

func (*MockClient) GetCalls

func (mc *MockClient) GetCalls() []MockCall

GetCalls returns all recorded calls.

func (*MockClient) OnDelete

func (mc *MockClient) OnDelete(path string, statusCode int, body []byte) *MockClient

OnDelete sets mock response for DELETE request.

func (*MockClient) OnError

func (mc *MockClient) OnError(method, path string, err error) *MockClient

OnError sets error for a request.

func (*MockClient) OnGet

func (mc *MockClient) OnGet(path string, statusCode int, body []byte) *MockClient

OnGet sets mock response for GET request.

func (*MockClient) OnPatch

func (mc *MockClient) OnPatch(path string, statusCode int, body []byte) *MockClient

OnPatch sets mock response for PATCH request.

func (*MockClient) OnPost

func (mc *MockClient) OnPost(path string, statusCode int, body []byte) *MockClient

OnPost sets mock response for POST request.

func (*MockClient) OnPut

func (mc *MockClient) OnPut(path string, statusCode int, body []byte) *MockClient

OnPut sets mock response for PUT request.

func (*MockClient) Patch

func (mc *MockClient) Patch(ctx context.Context, path string, body any) (*Response, error)

Patch mocks PATCH request.

func (*MockClient) Post

func (mc *MockClient) Post(ctx context.Context, path string, body any) (*Response, error)

Post mocks POST request.

func (*MockClient) Put

func (mc *MockClient) Put(ctx context.Context, path string, body any) (*Response, error)

Put mocks PUT request.

func (*MockClient) Reset

func (mc *MockClient) Reset()

Reset clears all mocks and recorded calls.

type Option

type Option func(*Client)

Option configures the Client.

func WithCircuitBreaker

func WithCircuitBreaker(threshold int, timeout time.Duration) Option

WithCircuitBreaker enables the circuit breaker with the given threshold and timeout.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the structured logger.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the maximum number of retry attempts.

func WithMaxRetryDelay

func WithMaxRetryDelay(d time.Duration) Option

WithMaxRetryDelay sets the maximum delay between retries.

func WithRetryDelay

func WithRetryDelay(d time.Duration) Option

WithRetryDelay sets the initial delay between retries.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP request timeout.

func WithTransport

func WithTransport(t http.RoundTripper) Option

WithTransport sets the HTTP transport.

type RequestBuilder

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

RequestBuilder builds HTTP requests with fluent API

func (*RequestBuilder) BearerToken

func (rb *RequestBuilder) BearerToken(token string) *RequestBuilder

BearerToken sets Authorization header

func (*RequestBuilder) Body

func (rb *RequestBuilder) Body(body any) *RequestBuilder

Body sets the request body

func (*RequestBuilder) Delete

func (rb *RequestBuilder) Delete(ctx context.Context) (*Response, error)

Delete is a shorthand for Method("DELETE").Send()

func (*RequestBuilder) Get

func (rb *RequestBuilder) Get(ctx context.Context) (*Response, error)

Get is a shorthand for Method("GET").Send()

func (*RequestBuilder) Header

func (rb *RequestBuilder) Header(key, value string) *RequestBuilder

Header sets a request header

func (*RequestBuilder) Headers

func (rb *RequestBuilder) Headers(headers map[string]string) *RequestBuilder

Headers sets multiple headers

func (*RequestBuilder) Method

func (rb *RequestBuilder) Method(method string) *RequestBuilder

Method sets the HTTP method

func (*RequestBuilder) Param

func (rb *RequestBuilder) Param(key, value string) *RequestBuilder

Param sets a query parameter

func (*RequestBuilder) Params

func (rb *RequestBuilder) Params(params map[string]string) *RequestBuilder

Params sets multiple query parameters

func (*RequestBuilder) Path

func (rb *RequestBuilder) Path(path string) *RequestBuilder

Path sets the request path

func (*RequestBuilder) Post

func (rb *RequestBuilder) Post(ctx context.Context) (*Response, error)

Post is a shorthand for Method("POST").Send()

func (*RequestBuilder) Put

func (rb *RequestBuilder) Put(ctx context.Context) (*Response, error)

Put is a shorthand for Method("PUT").Send()

func (*RequestBuilder) Send

func (rb *RequestBuilder) Send(ctx context.Context) (*Response, error)

Send executes the request

type Response

type Response struct {
	StatusCode int
	Status     string
	Headers    http.Header
	Body       []byte
	Duration   time.Duration
}

Response represents an HTTP response

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError returns true if status code is 4xx

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError returns true if status code is 5xx

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if status code is 2xx

func (*Response) JSON

func (r *Response) JSON(v any) error

JSON unmarshals response body into v

func (*Response) String

func (r *Response) String() string

String returns response body as string

Jump to

Keyboard shortcuts

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