http

package module
v1.15.2 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2025 License: BSD-2-Clause Imports: 36 Imported by: 22

README ΒΆ

HTTP Library

A comprehensive Go HTTP utilities library providing robust server and client functionality with extensive middleware capabilities, graceful shutdown support, and production-ready features.

Features

πŸš€ HTTP Server
  • Graceful shutdown with context cancellation
  • TLS support with automatic certificate handling
  • Background request processing for long-running operations
  • JSON response handlers with automatic content-type headers
  • Error handling middleware with structured error responses
  • Profiling endpoints (CPU, memory, pprof) for debugging
  • File serving capabilities
πŸ”§ HTTP Client & RoundTrippers
  • Retry logic with configurable delays and skip conditions
  • Rate limiting to prevent API abuse
  • Authentication (Basic Auth, Header-based)
  • Request/response logging with configurable verbosity
  • Metrics collection (Prometheus compatible)
  • Header manipulation and path prefix removal
  • Request building utilities
πŸ›‘οΈ Proxy & Middleware
  • Reverse proxy with error handling
  • Sentry integration for error reporting
  • Background handlers for async processing
  • Content type utilities
  • Request validation and response checking

Installation

go get github.com/bborbe/http

Quick Start

Basic HTTP Server
package main

import (
    "context"
    "net/http"
    
    bhttp "github.com/bborbe/http"
    "github.com/bborbe/run"
    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("OK"))
    })
    
    server := bhttp.NewServerWithPort(8080, router)
    run.CancelOnInterrupt(context.Background(), server)
}
JSON Handler
type Response struct {
    Message string `json:"message"`
    Status  string `json:"status"`
}

func healthHandler(ctx context.Context, req *http.Request) (interface{}, error) {
    return Response{
        Message: "Service is healthy",
        Status:  "OK",
    }, nil
}

func main() {
    router := mux.NewRouter()
    
    // JSON handler automatically sets Content-Type and marshals response
    jsonHandler := bhttp.NewJsonHandler(bhttp.JsonHandlerFunc(healthHandler))
    errorHandler := bhttp.NewErrorHandler(jsonHandler)
    
    router.Handle("/api/health", errorHandler)
    
    server := bhttp.NewServerWithPort(8080, router)
    run.CancelOnInterrupt(context.Background(), server)
}
HTTP Client with Retry
package main

import (
    "context"
    "net/http"
    "time"
    
    bhttp "github.com/bborbe/http"
)

func main() {
    // Create HTTP client with retry logic
    transport := bhttp.NewRoundTripperRetry(
        http.DefaultTransport,
        3,                    // retry limit
        time.Second * 2,      // retry delay
    )
    
    client := &http.Client{
        Transport: transport,
        Timeout:   time.Second * 30,
    }
    
    // Make request - automatically retries on failure
    resp, err := client.Get("https://api.example.com/data")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
}
Background Request Handler
func longRunningTask(ctx context.Context, req *http.Request) error {
    // Simulate long-running task
    time.Sleep(10 * time.Second)
    
    // Your background processing logic here
    return nil
}

func main() {
    router := mux.NewRouter()
    
    // Background handler processes requests asynchronously
    bgHandler := bhttp.NewBackgroundRequestHandler(
        bhttp.BackgroundRequestHandlerFunc(longRunningTask),
    )
    errorHandler := bhttp.NewErrorHandler(bgHandler)
    
    router.Handle("/api/process", errorHandler)
    
    server := bhttp.NewServerWithPort(8080, router)
    run.CancelOnInterrupt(context.Background(), server)
}
HTTP Proxy
func main() {
    targetURL, _ := url.Parse("https://api.backend.com")
    
    // Create proxy with error handling
    errorHandler := bhttp.NewProxyErrorHandler()
    transport := http.DefaultTransport
    
    proxy := bhttp.NewProxy(transport, targetURL, errorHandler)
    
    server := bhttp.NewServerWithPort(8080, proxy)
    run.CancelOnInterrupt(context.Background(), server)
}
Advanced Client with Middleware Stack
func main() {
    // Build client with multiple middleware layers
    transport := http.DefaultTransport
    
    // Add retry logic
    transport = bhttp.NewRoundTripperRetry(transport, 3, time.Second*2)
    
    // Add authentication
    transport = bhttp.NewRoundTripperBasicAuth(transport, "username", "password")
    
    // Add logging
    transport = bhttp.NewRoundTripperLog(transport)
    
    // Add rate limiting
    transport = bhttp.NewRoundTripperRateLimit(transport, 10) // 10 req/sec
    
    client := &http.Client{
        Transport: transport,
        Timeout:   time.Second * 30,
    }
    
    // Client now has retry, auth, logging, and rate limiting
    resp, err := client.Get("https://api.example.com/protected")
    // Handle response...
}

Testing

The library includes comprehensive test coverage and mock generation using Counterfeiter:

# Run tests
make test

# Run all quality checks (format, test, lint, etc.)
make precommit

# Generate mocks for testing
make generate
Pre-generated Mocks

The library provides pre-generated mocks in the mocks/ package for easy testing:

import "github.com/bborbe/http/mocks"

// Available mocks:
// - HttpHandler
// - HttpJsonHandler  
// - HttpJsonHandlerTx
// - HttpProxyErrorHandler
// - HttpRoundtripper
// - HttpRoundtripperMetrics
// - HttpWithError

Example usage in tests:

func TestMyService(t *testing.T) {
    mockHandler := &mocks.HttpJsonHandler{}
    mockHandler.ServeHTTPReturns(map[string]string{"status": "ok"}, nil)
    
    // Use mock in your test...
}

Advanced Features

Profiling Support

Built-in handlers for performance profiling:

  • CPU profiling: /debug/pprof/profile
  • Memory profiling: /debug/pprof/heap
  • Goroutine profiling: /debug/pprof/goroutine
Metrics Integration

Prometheus-compatible metrics collection for monitoring request performance, error rates, and more.

Error Handling

Structured error handling with context preservation and optional Sentry integration for production error tracking.

Graceful Shutdown

All server components support graceful shutdown with proper resource cleanup when receiving termination signals.

API Documentation

Complete API documentation is available on pkg.go.dev.

View the documentation locally with:

go doc -all github.com/bborbe/http

Dependencies

This library uses minimal external dependencies:

  • Standard net/http package
  • github.com/bborbe/errors for enhanced error handling
  • github.com/bborbe/run for graceful lifecycle management
  • Optional Prometheus metrics support
  • Optional Sentry error reporting

License

BSD-style license. See LICENSE file for details.

Documentation ΒΆ

Overview ΒΆ

Package http provides comprehensive HTTP utilities for building robust server and client applications.

The package offers three main categories of functionality:

HTTP Server Components ΒΆ

Server utilities with graceful shutdown support:

  • NewServer and NewServerWithPort for creating HTTP servers
  • NewServerTLS for HTTPS servers with certificate handling
  • Background request handlers for async processing
  • JSON response handlers with automatic content-type management
  • Error handling middleware with structured responses
  • Profiling endpoints for debugging (CPU, memory, pprof)

HTTP Client Components ΒΆ

RoundTripper middleware for HTTP clients:

  • Retry logic with configurable delays and skip conditions
  • Rate limiting to prevent API abuse
  • Authentication (Basic Auth, Header-based)
  • Request/response logging with configurable verbosity
  • Metrics collection (Prometheus compatible)
  • Header manipulation and path prefix removal

Proxy and Middleware ΒΆ

Proxy utilities and additional middleware:

  • Reverse proxy with error handling
  • Sentry integration for error reporting
  • Content type utilities
  • Request validation and response checking

Example Usage ΒΆ

Basic HTTP server:

router := mux.NewRouter()
router.HandleFunc("/health", healthHandler)
server := http.NewServerWithPort(8080, router)
run.CancelOnInterrupt(context.Background(), server)

HTTP client with retry:

transport := http.NewRoundTripperRetry(http.DefaultTransport, 3, time.Second*2)
client := &http.Client{Transport: transport}

JSON handler:

jsonHandler := http.NewJsonHandler(http.JsonHandlerFunc(myHandler))
errorHandler := http.NewErrorHandler(jsonHandler)
router.Handle("/api/data", errorHandler)

Index ΒΆ

Constants ΒΆ

View Source
const (
	// ApplicationJsonContentType is the MIME type for JSON responses.
	ApplicationJsonContentType = "application/json"
	// TextHtml is the MIME type for HTML responses.
	TextHtml = "text/html"
)
View Source
const (
	// ContentTypeHeaderName is the standard HTTP header name for content type.
	ContentTypeHeaderName = "Content-Type"
)
View Source
const PreventRetryHeaderName = "X-Prevent-Retry"

PreventRetryHeaderName is the HTTP header name used to disable retry logic. When this header is present in a request, the retry RoundTripper will not attempt retries.

Variables ΒΆ

View Source
var NotFound = stderrors.New("not found")

NotFound is a sentinel error used to indicate that a requested resource was not found.

Functions ΒΆ

func BuildRequest ΒΆ

func BuildRequest(
	ctx context.Context,
	method string,
	urlString string,
	parameters url.Values,
	body io.Reader,
	header http.Header,
) (*http.Request, error)

BuildRequest creates an HTTP request with the specified parameters. It constructs a request with the given method, URL, query parameters, body, and headers. The parameters argument contains URL query parameters that are properly encoded and appended to the URL query string. Any existing query parameters in the URL are replaced.

func CheckResponseIsSuccessful ΒΆ

func CheckResponseIsSuccessful(req *http.Request, resp *http.Response) error

CheckResponseIsSuccessful validates that an HTTP response indicates success. It returns NotFound error for 404 responses, and RequestFailedError for other non-success status codes. Success is defined as 2xx or 3xx status codes. The response body is preserved for further reading.

func CreateDefaultHttpClient ΒΆ

func CreateDefaultHttpClient() *http.Client

CreateDefaultHttpClient creates an HTTP client with default configuration. It uses a 30-second timeout and the default RoundTripper with retry logic and logging. The client disables automatic redirects by returning ErrUseLastResponse.

func CreateHttpClient ΒΆ

func CreateHttpClient(
	timeout time.Duration,
) *http.Client

CreateHttpClient creates an HTTP client with the specified timeout. It uses the default RoundTripper with retry logic and logging, and disables automatic redirects. The timeout applies to the entire request including connection, redirects, and reading the response.

func CreateTlsClientConfig ΒΆ

func CreateTlsClientConfig(
	ctx context.Context,
	caCertPath string,
	clientCertPath string,
	clientKeyPath string,
) (*tls.Config, error)

CreateTlsClientConfig creates a TLS configuration for mutual TLS authentication. It loads the CA certificate for server verification and the client certificate for client authentication. The configuration enforces server certificate verification (InsecureSkipVerify is false).

func FileServer ΒΆ

func FileServer(
	root string,
	prefix string,
) http.Handler

FileServer creates an HTTP handler that serves files from the specified root directory. It serves files with the given path prefix and automatically serves index.html for missing files. This is useful for serving single-page applications where all routes should serve the main HTML file.

func IsIgnoredSentryError ΒΆ

func IsIgnoredSentryError(err error) bool

IsIgnoredSentryError determines whether an error should be ignored when reporting to Sentry. It returns true for common transient errors like context cancellation, timeouts, and other retryable errors. This helps reduce noise in Sentry by filtering out expected operational errors.

func IsRetryError ΒΆ

func IsRetryError(err error) bool

IsRetryError determines whether an error should trigger a retry attempt. It checks for common transient errors like EOF, connection refused, timeouts, and handler timeouts. Returns true if the error is considered retryable, false otherwise.

func NewBackgroundRunHandler ΒΆ

func NewBackgroundRunHandler(ctx context.Context, runFunc run.Func) http.Handler

NewBackgroundRunHandler creates an HTTP handler that executes a run.Func in the background. When the endpoint is called, it triggers the runFunc asynchronously and immediately returns a response. The handler uses a ParallelSkipper to prevent multiple concurrent executions of the same function.

func NewBackgroundRunRequestHandler ΒΆ added in v1.14.0

func NewBackgroundRunRequestHandler(
	ctx context.Context,
	runFunc BackgroundRunRequestFunc,
) http.Handler

NewBackgroundRunRequestHandler creates an HTTP handler that executes the given function in the background. When the endpoint is called, it triggers the runFunc asynchronously with access to the HTTP request. The handler uses a ParallelSkipper to prevent multiple concurrent executions and returns immediately.

func NewErrorHandler ΒΆ

func NewErrorHandler(withError WithError) http.Handler

NewErrorHandler wraps a WithError handler to provide centralized error handling. It converts errors to HTTP responses with appropriate status codes and logs the results. If the error implements ErrorWithStatusCode, it uses that status code; otherwise defaults to 500.

func NewGarbageCollectorHandler ΒΆ added in v1.12.0

func NewGarbageCollectorHandler() http.Handler

func NewMetricsRoundTripper ΒΆ added in v1.13.0

func NewMetricsRoundTripper(
	roundTripper http.RoundTripper,
	metrics RoundTripperMetrics,
) http.RoundTripper

NewMetricsRoundTripper wraps a given RoundTripper and adds Prometheus metrics.

func NewPrintHandler ΒΆ

func NewPrintHandler(format string, a ...any) http.Handler

func NewProxy ΒΆ

func NewProxy(
	transport http.RoundTripper,
	apiUrl *url.URL,
	proxyErrorHandler ProxyErrorHandler,
) http.Handler

NewProxy creates a reverse proxy that forwards requests to the specified URL. It uses the provided transport for making upstream requests and handles errors with the given error handler. The proxy automatically sets the Host header to match the target URL.

func NewRoundTripperBasicAuth ΒΆ

func NewRoundTripperBasicAuth(
	roundTripper RoundTripper,
	username string,
	password string,
) http.RoundTripper

NewRoundTripperBasicAuth wraps a RoundTripper with HTTP Basic Authentication. It automatically adds Basic Auth headers to all requests using the provided username and password. If either username or password is empty, no authentication header is added.

func NewRoundTripperHeader ΒΆ

func NewRoundTripperHeader(
	roundTripper http.RoundTripper,
	header http.Header,
) http.RoundTripper

NewRoundTripperHeader wraps a RoundTripper to add custom headers to all requests. The provided headers are added to every request, replacing any existing headers with the same keys. This is useful for adding authentication headers, API keys, or other standard headers.

func NewRoundTripperLog ΒΆ

func NewRoundTripperLog(tripper http.RoundTripper) http.RoundTripper

NewRoundTripperLog wraps a RoundTripper with request/response logging. It logs the HTTP method, URL, status code, duration, and any errors at verbose level 2. This is useful for debugging and monitoring HTTP client behavior.

func NewRoundTripperRateLimit ΒΆ

func NewRoundTripperRateLimit(
	ctx context.Context,
	tripper http.RoundTripper,
	maxRequestPerInterval int64,
	intervalDurarion time.Duration,
	logSamplerFactory log.SamplerFactory,
) http.RoundTripper

NewRoundTripperRateLimit wraps a RoundTripper with rate limiting functionality. It limits the number of requests to maxRequestPerInterval within each intervalDuration window. When the limit is exceeded, requests are delayed rather than rejected. The logSamplerFactory is used to sample rate limit messages to reduce log noise.

func NewRoundTripperRemovePathPrefix ΒΆ

func NewRoundTripperRemovePathPrefix(
	roundTripper http.RoundTripper,
	prefix string,
) http.RoundTripper

NewRoundTripperRemovePathPrefix wraps a RoundTripper to remove a path prefix from request URLs. If the request URL path starts with the specified prefix, it removes that prefix before forwarding the request. This is useful for proxying requests where the upstream service expects different path structures.

func NewRoundTripperRetry ΒΆ

func NewRoundTripperRetry(
	roundTripper http.RoundTripper,
	retryLimit int,
	retryDelay time.Duration,
) http.RoundTripper

NewRoundTripperRetry wraps a RoundTripper with retry logic using default skip status codes. It will retry failed requests up to retryLimit times with retryDelay between attempts. Requests with 400, 401, and 404 status codes are not retried as they indicate client errors.

func NewRoundTripperRetryWithSkipStatus ΒΆ added in v1.8.1

func NewRoundTripperRetryWithSkipStatus(
	roundTripper http.RoundTripper,
	retryLimit int,
	retryDelay time.Duration,
	skipStatusCodes []int,
) http.RoundTripper

NewRoundTripperRetryWithSkipStatus wraps a RoundTripper with retry logic and custom skip status codes. It allows specifying which HTTP status codes should not trigger retries. This is useful when you want to customize which responses are considered permanent failures.

func NewServer ΒΆ

func NewServer(addr string, router http.Handler) run.Func

NewServer creates an HTTP server that listens on the specified address. It returns a run.Func that handles graceful shutdown when the context is cancelled. The addr parameter should be in the format ":port" or "host:port".

func NewServerTLS ΒΆ

func NewServerTLS(
	addr string,
	router http.Handler,
	serverCertPath string,
	serverKeyPath string,
) run.Func

NewServerTLS creates an HTTPS server with TLS support. It listens on the specified address using the provided certificate and key files. The server includes error log filtering to skip common TLS handshake errors. Returns a run.Func for graceful shutdown management.

func NewServerWithPort ΒΆ

func NewServerWithPort(port int, router http.Handler) run.Func

NewServerWithPort creates an HTTP server that listens on the specified port. It returns a run.Func that can be used with the run package for graceful shutdown. The server will bind to all interfaces on the given port (e.g., port 8080 becomes ":8080").

func NewSkipErrorWriter ΒΆ

func NewSkipErrorWriter(writer io.Writer) io.Writer

NewSkipErrorWriter creates a writer that filters out TLS handshake error messages. It wraps the given writer and skips writing messages containing "http: TLS handshake error from". This is useful for reducing noise in server logs when dealing with automated scanners or bots.

func NewUpdateErrorHandler ΒΆ added in v1.8.0

func NewUpdateErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler

func NewViewErrorHandler ΒΆ added in v1.8.0

func NewViewErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler

func RegisterPprof ΒΆ

func RegisterPprof(router *mux.Router)

RegisterPprof register pprof http endpoint to gorilla mux https://www.codereliant.io/memory-leaks-with-pprof/ kubectl -n erpnext port-forward service/hubspot-resource-exporter 9090:9090 go tool pprof -alloc_space http://localhost:9090/debug/pprof/heap > web or go tool pprof -http=127.0.0.1:16666 -alloc_space http://localhost:9090/debug/pprof/heap

func WriteAndGlog ΒΆ

func WriteAndGlog(w io.Writer, format string, a ...any) (n int, err error)

WriteAndGlog writes formatted text to both a writer and the glog at verbose level 2. It formats the message using fmt.Printf-style formatting and writes it to the writer with a newline. The same message is also logged using glog.V(2).InfoDepthf for debugging purposes.

Types ΒΆ

type BackgroundRunRequestFunc ΒΆ added in v1.14.0

type BackgroundRunRequestFunc func(ctx context.Context, req *http.Request) error

BackgroundRunRequestFunc defines a function that processes HTTP requests in the background. The function receives the request context and the HTTP request for processing.

type CheckRedirect ΒΆ

type CheckRedirect func(req *http.Request, via []*http.Request) error

CheckRedirect defines a function that controls the behavior of redirects. It receives the upcoming request and the requests made already in oldest-to-newest order.

type DialFunc ΒΆ

type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)

DialFunc defines a function that establishes network connections. It should return a connection to the given network address.

type ErrorWithStatusCode ΒΆ added in v1.9.0

type ErrorWithStatusCode interface {
	error
	StatusCode() int
}

ErrorWithStatusCode defines an error that can provide an HTTP status code. This interface allows errors to specify which HTTP status code should be returned to clients.

func WrapWithStatusCode ΒΆ added in v1.9.0

func WrapWithStatusCode(err error, code int) ErrorWithStatusCode

WrapWithStatusCode wraps a existing error with statusCode used by ErrorHandler

type Handler ΒΆ added in v1.11.0

type Handler http.Handler

Handler is an alias for http.Handler to enable mock generation. It provides the same interface as the standard library's Handler for HTTP request handling.

type HandlerFunc ΒΆ added in v1.11.0

type HandlerFunc http.HandlerFunc

HandlerFunc is an alias for http.HandlerFunc to enable mock generation. It provides the same interface as the standard library's HandlerFunc for HTTP request handling.

type HasTemporaryError ΒΆ

type HasTemporaryError interface {
	Temporary() bool
}

HasTemporaryError defines an interface for errors that can indicate temporary conditions. Errors implementing this interface can be checked for temporary failure status.

type HasTimeoutError ΒΆ

type HasTimeoutError interface {
	Timeout() bool
}

HasTimeoutError defines an interface for errors that can indicate timeout conditions. Errors implementing this interface can be checked for timeout status.

type HttpClientBuilder ΒΆ

type HttpClientBuilder interface {
	WithRetry(retryLimit int, retryDelay time.Duration) HttpClientBuilder
	WithoutRetry() HttpClientBuilder
	WithProxy() HttpClientBuilder
	WithoutProxy() HttpClientBuilder
	// WithRedirects controls how many redirects are allowed
	// 0 = no redirects, -1 = infinit redirects, 10 = 10 max redirects
	WithRedirects(maxRedirect int) HttpClientBuilder
	// WithoutRedirects is equal to WithRedirects(0)
	WithoutRedirects() HttpClientBuilder
	WithTimeout(timeout time.Duration) HttpClientBuilder
	WithDialFunc(dialFunc DialFunc) HttpClientBuilder
	WithInsecureSkipVerify(insecureSkipVerify bool) HttpClientBuilder
	WithClientCert(caCertPath string, clientCertPath string, clientKeyPath string) HttpClientBuilder
	Build(ctx context.Context) (*http.Client, error)
	BuildRoundTripper(ctx context.Context) (http.RoundTripper, error)
}

HttpClientBuilder defines the interface for building configured HTTP clients. It provides a fluent API for configuring various aspects of HTTP client behavior.

func NewClientBuilder ΒΆ

func NewClientBuilder() HttpClientBuilder

NewClientBuilder creates a new HTTP client builder with sensible defaults. Default configuration includes: no proxy, max 10 redirects, 30 second timeout, no retry.

type JsonHandler ΒΆ

type JsonHandler interface {
	ServeHTTP(ctx context.Context, req *http.Request) (interface{}, error)
}

JsonHandler defines the interface for handlers that return JSON responses. Implementations should return the data to be JSON-encoded and any error that occurred.

type JsonHandlerFunc ΒΆ

type JsonHandlerFunc func(ctx context.Context, req *http.Request) (interface{}, error)

JsonHandlerFunc is an adapter to allow the use of ordinary functions as JsonHandlers. If f is a function with the appropriate signature, JsonHandlerFunc(f) is a JsonHandler that calls f.

func (JsonHandlerFunc) ServeHTTP ΒΆ

func (j JsonHandlerFunc) ServeHTTP(ctx context.Context, req *http.Request) (interface{}, error)

ServeHTTP calls f(ctx, req).

type JsonHandlerTx ΒΆ added in v1.8.0

type JsonHandlerTx interface {
	ServeHTTP(ctx context.Context, tx libkv.Tx, req *http.Request) (interface{}, error)
}

JsonHandlerTx defines the interface for handlers that return JSON responses within database transactions. Implementations should return the data to be JSON-encoded and any error that occurred.

type JsonHandlerTxFunc ΒΆ added in v1.8.0

type JsonHandlerTxFunc func(ctx context.Context, tx libkv.Tx, req *http.Request) (interface{}, error)

JsonHandlerTxFunc is an adapter to allow the use of ordinary functions as JsonHandlerTx handlers. If f is a function with the appropriate signature, JsonHandlerTxFunc(f) is a JsonHandlerTx that calls f.

func (JsonHandlerTxFunc) ServeHTTP ΒΆ added in v1.8.0

func (j JsonHandlerTxFunc) ServeHTTP(
	ctx context.Context,
	tx libkv.Tx,
	req *http.Request,
) (interface{}, error)

ServeHTTP calls f(ctx, tx, req).

type Proxy ΒΆ

type Proxy func(req *http.Request) (*url.URL, error)

Proxy defines a function that determines which proxy to use for a given request. It returns the proxy URL to use, or nil if no proxy should be used.

type ProxyErrorHandler ΒΆ

type ProxyErrorHandler interface {
	HandleError(resp http.ResponseWriter, req *http.Request, err error)
}

ProxyErrorHandler defines the interface for handling errors that occur in reverse proxy operations. Implementations should handle the error appropriately, such as returning error responses to clients.

func NewSentryProxyErrorHandler ΒΆ

func NewSentryProxyErrorHandler(sentryClient libsentry.Client) ProxyErrorHandler

NewSentryProxyErrorHandler creates a ProxyErrorHandler that reports errors to Sentry. It logs errors and sends them to Sentry unless they are ignored errors (like timeouts or retryable errors). The handler returns a 502 Bad Gateway status for all proxy errors.

type ProxyErrorHandlerFunc ΒΆ

type ProxyErrorHandlerFunc func(resp http.ResponseWriter, req *http.Request, err error)

ProxyErrorHandlerFunc is an adapter to allow the use of ordinary functions as ProxyErrorHandler. If f is a function with the appropriate signature, ProxyErrorHandlerFunc(f) is a ProxyErrorHandler that calls f.

func (ProxyErrorHandlerFunc) HandleError ΒΆ

func (p ProxyErrorHandlerFunc) HandleError(resp http.ResponseWriter, req *http.Request, err error)

HandleError calls f(resp, req, err).

type RequestFailedError ΒΆ

type RequestFailedError struct {
	Method     string
	URL        string
	StatusCode int
}

RequestFailedError represents an HTTP request that failed with a non-success status code. It contains information about the failed request including method, URL, and status code.

func (RequestFailedError) Error ΒΆ

func (r RequestFailedError) Error() string

type RoundTripper ΒΆ

type RoundTripper http.RoundTripper

RoundTripper is an alias for http.RoundTripper to enable mock generation. It provides the same interface as the standard library's RoundTripper for HTTP transport.

func CreateDefaultRoundTripper ΒΆ

func CreateDefaultRoundTripper() RoundTripper

CreateDefaultRoundTripper creates a RoundTripper with default configuration. It includes retry logic (5 retries with 1 second delay) and request/response logging. The transport uses standard HTTP/2 settings with reasonable timeouts.

func CreateDefaultRoundTripperTls ΒΆ

func CreateDefaultRoundTripperTls(
	ctx context.Context,
	caCertPath string,
	clientCertPath string,
	clientKeyPath string,
) (RoundTripper, error)

CreateDefaultRoundTripperTls creates a RoundTripper with TLS client certificate authentication. It loads the specified CA certificate, client certificate, and private key for mutual TLS authentication. The returned RoundTripper includes the same retry logic and logging as CreateDefaultRoundTripper.

type RoundTripperFunc ΒΆ

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

RoundTripperFunc is an adapter to allow the use of ordinary functions as http.RoundTripper. If f is a function with the appropriate signature, RoundTripperFunc(f) is a RoundTripper that calls f.

func (RoundTripperFunc) RoundTrip ΒΆ

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

RoundTrip calls f(req).

type RoundTripperMetrics ΒΆ added in v1.13.0

type RoundTripperMetrics interface {
	TotalCounterInc(host string, method string)
	SuccessCounterInc(host string, method string, statusCode int)
	FailureCounterInc(host string, method string)
	DurationMeasureObserve(host string, method string, duration time.Duration)
}

RoundTripperMetrics defines the interface for collecting HTTP request metrics. It provides methods to record various metrics about HTTP requests including counts, status codes, and durations.

func NewRoundTripperMetrics ΒΆ added in v1.13.0

func NewRoundTripperMetrics() RoundTripperMetrics

NewRoundTripperMetrics creates a new RoundTripperMetrics implementation that uses Prometheus metrics. The returned instance will record metrics to the default Prometheus registry.

type WithError ΒΆ

type WithError interface {
	ServeHTTP(ctx context.Context, resp http.ResponseWriter, req *http.Request) error
}

WithError defines the interface for HTTP handlers that can return errors. Unlike standard http.Handler, this interface allows returning errors for centralized error handling.

func NewCpuProfileStartHandler ΒΆ

func NewCpuProfileStartHandler() WithError

func NewCpuProfileStopHandler ΒΆ

func NewCpuProfileStopHandler() WithError

func NewFileDownloader ΒΆ

func NewFileDownloader(path string) WithError

func NewJsonHandler ΒΆ

func NewJsonHandler(jsonHandler JsonHandler) WithError

NewJsonHandler wraps a JsonHandler to automatically encode responses as JSON. It sets the appropriate Content-Type header and handles JSON marshaling. Returns a WithError handler that can be used with error handling middleware.

func NewJsonHandlerUpdateTx ΒΆ added in v1.8.0

func NewJsonHandlerUpdateTx(db libkv.DB, jsonHandler JsonHandlerTx) WithError

NewJsonHandlerUpdateTx wraps a JsonHandlerTx to automatically encode responses as JSON within a read-write database transaction. It executes the handler within a database update transaction and handles JSON marshaling. Returns a WithError handler that can be used with error handling middleware.

func NewJsonHandlerViewTx ΒΆ added in v1.8.0

func NewJsonHandlerViewTx(db libkv.DB, jsonHandler JsonHandlerTx) WithError

NewJsonHandlerViewTx wraps a JsonHandlerTx to automatically encode responses as JSON within a read-only database transaction. It executes the handler within a database view transaction and handles JSON marshaling. Returns a WithError handler that can be used with error handling middleware.

func NewMemoryProfileHandler ΒΆ

func NewMemoryProfileHandler() WithError

func NewProfilingStart ΒΆ

func NewProfilingStart() WithError

func NewProfilingStop ΒΆ

func NewProfilingStop() WithError

type WithErrorFunc ΒΆ

type WithErrorFunc func(ctx context.Context, resp http.ResponseWriter, req *http.Request) error

WithErrorFunc is an adapter to allow the use of ordinary functions as WithError handlers. If f is a function with the appropriate signature, WithErrorFunc(f) is a WithError that calls f.

func (WithErrorFunc) ServeHTTP ΒΆ

func (w WithErrorFunc) ServeHTTP(
	ctx context.Context,
	resp http.ResponseWriter,
	req *http.Request,
) error

ServeHTTP calls f(ctx, resp, req).

type WithErrorTx ΒΆ added in v1.8.0

type WithErrorTx interface {
	ServeHTTP(ctx context.Context, tx libkv.Tx, resp http.ResponseWriter, req *http.Request) error
}

WithErrorTx defines the interface for HTTP handlers that can return errors and work with database transactions. This extends the WithError interface by providing access to a key-value transaction for database operations.

type WithErrorTxFunc ΒΆ added in v1.8.0

type WithErrorTxFunc func(ctx context.Context, tx libkv.Tx, resp http.ResponseWriter, req *http.Request) error

WithErrorTxFunc is an adapter to allow the use of ordinary functions as WithErrorTx handlers. If f is a function with the appropriate signature, WithErrorTxFunc(f) is a WithErrorTx that calls f.

func (WithErrorTxFunc) ServeHTTP ΒΆ added in v1.8.0

func (w WithErrorTxFunc) ServeHTTP(
	ctx context.Context,
	tx libkv.Tx,
	resp http.ResponseWriter,
	req *http.Request,
) error

ServeHTTP calls f(ctx, tx, resp, req).

Directories ΒΆ

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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