httpclient

package
v0.0.0-...-dfd3089 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

README

HTTP Client Package

A developer-friendly HTTP client package for the Cosmo Router Plugin. This package provides a simple, flexible, and feature-rich HTTP client implementation with a modern approach using functional options and generics.

Features

  • Simple, fluent API for making HTTP requests
  • Function options pattern for configuration
  • Context support for cancellation and timeouts
  • Middleware support for request customization
  • Generic response handling
  • Built-in middleware implementations for common use cases
  • Comprehensive test coverage

Installation

go get github.com/wundergraph/cosmo/router-plugin

Basic Usage

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/wundergraph/cosmo/router-plugin/httpclient"
)

func main() {
	// Create HTTP client with configuration options
	client := httpclient.New(
		httpclient.WithBaseURL("https://api.example.com"),
		httpclient.WithTimeout(10 * time.Second),
		httpclient.WithHeader("Accept", "application/json"),
	)

	// Create a context
	ctx := context.Background()

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

	// Check if the request was successful
	if !resp.IsSuccess() {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		return
	}

	// Parse the response into a struct using generics
	type User struct {
		ID    int    `json:"id"`
		Name  string `json:"name"`
		Email string `json:"email"`
	}

	user, err := httpclient.UnmarshalTo[User](resp)
	if err != nil {
		panic(err)
	}

	fmt.Printf("User: %s (Email: %s)\n", user.Name, user.Email)
}

Advanced Usage

Middleware

The client supports middleware for request customization:

// Create a client with middleware
client := httpclient.New(
	httpclient.WithBaseURL("https://api.example.com"),
	httpclient.WithMiddleware(httpclient.AuthBearerMiddleware("your-token")),
	httpclient.WithMiddleware(httpclient.UserAgentMiddleware("MyApp/1.0")),
)
Request-specific options

You can add headers or other options to specific requests:

// Make a request with specific headers
resp, err := client.Get(ctx, "/users/1", 
	httpclient.WithRequestHeader("X-Request-ID", "12345"),
)
POST requests with JSON body
// Create request body
newUser := struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}{
	Name:  "John Doe",
	Email: "john@example.com",
}

// Send POST request
resp, err := client.Post(ctx, "/users", newUser)

Middleware Implementations

The package includes several built-in middleware implementations:

  • AuthBearerMiddleware: Adds a Bearer token to the Authorization header
  • BasicAuthMiddleware: Adds basic authentication to the request

Custom Middleware

You can create your own middleware:

// Create a custom middleware
customMiddleware := func(req *http.Request) (*http.Request, error) {
	// Customize the request
	req.Header.Set("X-Custom-Header", "custom-value")
	return req, nil
}

// Add the middleware to the client
client := httpclient.New(
	httpclient.WithMiddleware(customMiddleware),
)

Error Handling

The client returns comprehensive errors that can be unwrapped:

resp, err := client.Get(ctx, "/users/1")
if err != nil {
	// Check for specific error types
	var urlErr *url.Error
	if errors.As(err, &urlErr) {
		fmt.Printf("URL error: %v\n", urlErr)
	} else {
		fmt.Printf("Other error: %v\n", err)
	}
	return
}

Response Helpers

The Response type provides helper methods:

  • Unmarshal(v interface{}): Decodes the response body into a struct
  • String(): Returns the response body as a string
  • IsSuccess(): Returns true if the status code is in the 2xx range

Documentation

Index

Constants

View Source
const (
	DefaultRetryMax     = 3
	DefaultRetryWaitMin = 1 * time.Second
	DefaultRetryWaitMax = 30 * time.Second
)

Default retry values

Variables

This section is empty.

Functions

func UnmarshalTo

func UnmarshalTo[T any](response *Response) (T, error)

UnmarshalTo is a generic helper to decode the response into a struct

Types

type Client

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

Client is a wrapper around http.Client with additional functionality

func New

func New(options ...ClientOption) *Client

New creates a new HTTP client with the given options

func (*Client) Delete

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

Delete sends a DELETE request and returns the response

func (*Client) Get

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

Get sends a GET request and returns the response

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, body interface{}, options ...RequestOption) (*Response, error)

Patch sends a PATCH request and returns the response

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body interface{}, options ...RequestOption) (*Response, error)

Post sends a POST request and returns the response

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body interface{}, options ...RequestOption) (*Response, error)

Put sends a PUT request and returns the response

func (*Client) Request

func (c *Client) Request(ctx context.Context, method, path string, body interface{}, options ...RequestOption) (*Response, error)

Request sends an HTTP request and returns the response

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures a Client

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL sets the base URL for the client

func WithHeader

func WithHeader(key, value string) ClientOption

WithHeader adds a header to all requests

func WithHeaders

func WithHeaders(headers map[string]string) ClientOption

WithHeaders adds multiple headers to all requests

func WithMiddleware

func WithMiddleware(middleware Middleware) ClientOption

WithMiddleware adds a middleware to the client

func WithRetry

func WithRetry(opts RetryOptions) ClientOption

WithRetry sets the retry options for the client

func WithRetryMax

func WithRetryMax(max int) ClientOption

WithRetryMax sets the maximum number of retries for the client

func WithRetryPolicy

func WithRetryPolicy(policy retryablehttp.CheckRetry) ClientOption

WithRetryPolicy sets a custom retry policy for the client

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout for the client

func WithTracing

func WithTracing() ClientOption

WithTracing enables tracing using a RoundTripper approach

func WithoutRetry

func WithoutRetry() ClientOption

WithoutRetry disables retries for the client

type Middleware

type Middleware func(req *http.Request) (*http.Request, error)

Middleware is a function that wraps an HTTP request

func AuthBearerMiddleware

func AuthBearerMiddleware(token string) Middleware

AuthBearerMiddleware adds a Bearer token to the Authorization header

func BasicAuthMiddleware

func BasicAuthMiddleware(username, password string) Middleware

BasicAuthMiddleware adds basic authentication to the request

type RequestOption

type RequestOption func(*requestOptions)

RequestOption is a function that configures a request

func WithRequestHeader

func WithRequestHeader(key, value string) RequestOption

WithRequestHeader adds a header to a specific request

type Response

type Response struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
}

Response is a wrapper around http.Response with additional functionality

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if the response status code is in the 2xx range

func (*Response) String

func (r *Response) String() string

String returns the response body as a string

func (*Response) Unmarshal

func (r *Response) Unmarshal(v interface{}) error

Unmarshal decodes the response body into the given value

type RetryOptions

type RetryOptions struct {
	// Enabled determines if retries are enabled
	Enabled bool

	// Max is the maximum number of retries
	Max int

	// WaitMin is the minimum time to wait between retries
	WaitMin time.Duration

	// WaitMax is the maximum time to wait between retries
	WaitMax time.Duration

	// CheckRetry specifies a policy for handling retries
	CheckRetry retryablehttp.CheckRetry
}

RetryOptions configures the retry behavior of the client

func DefaultRetryOptions

func DefaultRetryOptions() RetryOptions

DefaultRetryOptions returns the default retry options

Jump to

Keyboard shortcuts

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