httpclient

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package httpclient provides an HTTP/REST client with retry, circuit breaker, rate limiting, and comprehensive middleware support for CQI infrastructure. It wraps the resty library with CQI patterns for observability and error handling.

Example usage:

cfg := config.HTTPClientConfig{
    BaseURL:    "https://api.example.com",
    Timeout:    30 * time.Second,
    RetryCount: 3,
}

client, err := httpclient.New(ctx, cfg)
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// Make a GET request
resp, err := client.Get(ctx, "/users/123")
if err != nil {
    log.Fatal(err)
}

// Make a POST request with JSON body
user := map[string]string{"name": "John"}
resp, err = client.Post(ctx, "/users").WithJSON(user).Do()

// Use with protobuf
var userProto pb.User
resp, err = client.Get(ctx, "/users/123").IntoProto(&userProto).Do()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client provides HTTP/REST client functionality with retry, circuit breaker, rate limiting, and middleware support.

func New

New creates a new HTTP client with the provided configuration. It initializes connection pooling, retry logic, circuit breaker (if enabled), and rate limiting (if configured).

func (*Client) Close

func (c *Client) Close() error

Close releases all resources associated with the client. It cancels the client context and closes the circuit breaker.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, url string) *Request

Delete creates a new DELETE request for the specified URL.

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string) *Request

Get creates a new GET request for the specified URL. The URL can be relative (appended to BaseURL) or absolute.

func (*Client) Head

func (c *Client) Head(ctx context.Context, url string) *Request

Head creates a new HEAD request for the specified URL.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context) *Request

NewRequest creates a new request with the client's configuration.

func (*Client) Options

func (c *Client) Options(ctx context.Context, url string) *Request

Options creates a new OPTIONS request for the specified URL.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, url string) *Request

Patch creates a new PATCH request for the specified URL.

func (*Client) Post

func (c *Client) Post(ctx context.Context, url string) *Request

Post creates a new POST request for the specified URL.

func (*Client) Put

func (c *Client) Put(ctx context.Context, url string) *Request

Put creates a new PUT request for the specified URL.

func (*Client) WithAuthToken

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

WithAuthToken adds Bearer token authentication to all requests.

func (*Client) WithBasicAuth

func (c *Client) WithBasicAuth(username, password string) *Client

WithBasicAuth adds basic authentication to all requests.

func (*Client) WithDefaultHeader

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

WithDefaultHeader adds a default header to all requests.

func (*Client) WithDefaultHeaders

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

WithDefaultHeaders adds multiple default headers to all requests.

func (*Client) WithLogging

func (c *Client) WithLogging(logger *zerolog.Logger) *Client

WithLogging adds logging middleware to the HTTP client. It logs request start, response, duration, and status codes.

func (*Client) WithMetrics

func (c *Client) WithMetrics(namespace string) *Client

WithMetrics adds metrics middleware to the HTTP client. It records request count and duration for all HTTP requests.

func (*Client) WithTracing

func (c *Client) WithTracing(serviceName string) *Client

WithTracing adds distributed tracing middleware to the HTTP client. It creates spans for each request with appropriate attributes.

type Request

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

Request represents an HTTP request with a fluent builder API. It wraps resty.Request with CQI-specific features like protobuf support and error mapping.

func (*Request) Do

func (r *Request) Do() (*Response, error)

Do executes the request and returns the response. It enforces rate limiting, maps errors to CQI error types, and handles retries automatically.

func (*Request) IntoJSON

func (r *Request) IntoJSON(result interface{}) *Request

IntoJSON tells the request to unmarshal the response body into the provided struct.

func (*Request) IntoProto

func (r *Request) IntoProto(msg proto.Message) *Request

IntoProto tells the request to unmarshal the response body as a protobuf message.

func (*Request) SetMethod

func (r *Request) SetMethod(method string) *Request

SetMethod sets the HTTP method for the request.

func (*Request) SetURL

func (r *Request) SetURL(url string) *Request

SetURL sets the URL for the request. Can be relative (appended to BaseURL) or absolute.

func (*Request) WithAuthToken

func (r *Request) WithAuthToken(token string) *Request

WithAuthToken sets the Bearer authentication token.

func (*Request) WithBasicAuth

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

WithBasicAuth sets basic authentication credentials.

func (*Request) WithBody

func (r *Request) WithBody(body []byte) *Request

WithBody sets the request body as raw bytes.

func (*Request) WithFormData

func (r *Request) WithFormData(data map[string]string) *Request

WithFormData sets the request body as form data.

func (*Request) WithHeader

func (r *Request) WithHeader(key, value string) *Request

WithHeader sets a single header on the request.

func (*Request) WithHeaders

func (r *Request) WithHeaders(headers map[string]string) *Request

WithHeaders sets multiple headers on the request.

func (*Request) WithJSON

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

WithJSON sets the request body as JSON. The body is automatically serialized to JSON.

func (*Request) WithProto

func (r *Request) WithProto(msg proto.Message) *Request

WithProto sets the request body as a protobuf message. The message is serialized to wire format before sending.

func (*Request) WithQuery

func (r *Request) WithQuery(key, value string) *Request

WithQuery adds a single query parameter to the request.

func (*Request) WithQueryParams

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

WithQueryParams adds multiple query parameters to the request.

func (*Request) WithTimeout

func (r *Request) WithTimeout(timeout time.Duration) *Request

WithTimeout sets a custom timeout for this specific request. Overrides the client's default timeout.

type Response

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

Response wraps the resty response with CQI-specific error mapping and protobuf deserialization support.

func (*Response) Body

func (r *Response) Body() []byte

Body returns the raw response body as bytes.

func (*Response) BodyAsJSON

func (r *Response) BodyAsJSON(dest interface{}) error

BodyAsJSON unmarshals the response body into the provided struct.

func (*Response) BodyAsProto

func (r *Response) BodyAsProto(msg proto.Message) error

BodyAsProto unmarshals the response body as a protobuf message.

func (*Response) BodyAsString

func (r *Response) BodyAsString() string

BodyAsString returns the response body as a string.

func (*Response) Error

func (r *Response) Error() error

Error returns the error associated with this response, if any.

func (*Response) Header

func (r *Response) Header(key string) string

Header returns the value of a single header.

func (*Response) Headers

func (r *Response) Headers() http.Header

Headers returns all response headers.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if the status code is 4xx or 5xx.

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if the status code is 2xx.

func (*Response) Status

func (r *Response) Status() string

Status returns the HTTP status string (e.g., "200 OK").

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode returns the HTTP status code.

Jump to

Keyboard shortcuts

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