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
- Variables
- func BuildRequest(ctx context.Context, method string, urlString string, parameters url.Values, ...) (*http.Request, error)
- func CheckResponseIsSuccessful(req *http.Request, resp *http.Response) error
- func CreateDefaultHTTPClient() *http.Client
- func CreateDefaultHttpClient() *http.Clientdeprecated
- func CreateHTTPClient(timeout time.Duration) *http.Client
- func CreateHTTPServer(addr string, router http.Handler, serverOptions ServerOptions) *http.Server
- func CreateHttpClient(timeout time.Duration) *http.Clientdeprecated
- func CreateHttpServer(addr string, router http.Handler, serverOptions ServerOptions) *http.Serverdeprecated
- func CreateTLSClientConfig(ctx context.Context, caCertPath string, clientCertPath string, ...) (*tls.Config, error)
- func CreateTlsClientConfig(ctx context.Context, caCertPath string, clientCertPath string, ...) (*tls.Config, error)deprecated
- func FileServer(root string, prefix string) http.Handler
- func IsIgnoredSentryError(err error) bool
- func IsRetryError(err error) bool
- func NewBackgroundRunHandler(ctx context.Context, runFunc run.Func) http.Handler
- func NewBackgroundRunRequestHandler(ctx context.Context, runFunc BackgroundRunRequestFunc) http.Handler
- func NewDangerousHandlerWrapper(handler http.Handler) http.Handler
- func NewDangerousHandlerWrapperWithCurrentDateTime(handler http.Handler, currentDateTime libtime.CurrentDateTime) http.Handler
- func NewErrorHandler(withError WithError) http.Handler
- func NewGarbageCollectorHandler() http.Handler
- func NewJSONErrorHandler(withError WithError) http.Handler
- func NewJSONUpdateErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler
- func NewJSONViewErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler
- func NewMetricsRoundTripper(roundTripper http.RoundTripper, metrics RoundTripperMetrics) http.RoundTripper
- func NewPrintHandler(format string, a ...any) http.Handler
- func NewProxy(transport http.RoundTripper, apiURL *url.URL, ...) http.Handler
- func NewRoundTripperBasicAuth(roundTripper RoundTripper, username string, password string) http.RoundTripper
- func NewRoundTripperHeader(roundTripper http.RoundTripper, header http.Header) http.RoundTripper
- func NewRoundTripperLog(tripper http.RoundTripper) http.RoundTripper
- func NewRoundTripperRateLimit(ctx context.Context, tripper http.RoundTripper, maxRequestPerInterval int64, ...) http.RoundTripper
- func NewRoundTripperRemovePathPrefix(roundTripper http.RoundTripper, prefix string) http.RoundTripper
- func NewRoundTripperRetry(roundTripper http.RoundTripper, retryLimit int, retryDelay time.Duration) http.RoundTripper
- func NewRoundTripperRetryWithSkipStatus(roundTripper http.RoundTripper, retryLimit int, retryDelay time.Duration, ...) http.RoundTripper
- func NewServer(addr string, router http.Handler, ...) run.Func
- func NewServerTLS(addr string, router http.Handler, serverCertPath string, serverKeyPath string, ...) run.Func
- func NewServerWithPort(port int, router http.Handler, optionFns ...func(serverOptions *ServerOptions)) run.Func
- func NewSkipErrorWriter(writer io.Writer) io.Writer
- func NewUpdateErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler
- func NewViewErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler
- func RegisterPprof(router *mux.Router)
- func SendJSONFileResponse(ctx context.Context, resp http.ResponseWriter, data interface{}, ...) error
- func SendJSONResponse(ctx context.Context, resp http.ResponseWriter, data interface{}, ...) error
- func ValidateFilename(ctx context.Context, name string) error
- func WrapWithCode(err error, code string, statusCode int) error
- func WrapWithDetails(err error, code string, statusCode int, details map[string]any) error
- func WriteAndGlog(w io.Writer, format string, a ...any) (n int, err error)
- type BackgroundRunRequestFunc
- type CheckRedirect
- type ClientBuilder
- type DialFunc
- type ErrorDetails
- type ErrorResponse
- type ErrorWithCode
- type ErrorWithStatusCode
- type HTTPClientBuilderdeprecated
- type Handler
- type HandlerFunc
- type HasTemporaryError
- type HasTimeoutError
- type HttpClientBuilderdeprecated
- type JSONHandler
- type JSONHandlerFunc
- type JSONHandlerTx
- type JSONHandlerTxFunc
- type JsonHandlerdeprecated
- type JsonHandlerFuncdeprecated
- type JsonHandlerTxdeprecated
- type JsonHandlerTxFuncdeprecated
- type Proxy
- type ProxyErrorHandler
- type ProxyErrorHandlerFunc
- type RequestFailedError
- type RoundTripper
- func CreateDefaultRoundTripper() RoundTripper
- func CreateDefaultRoundTripperTLS(ctx context.Context, caCertPath string, clientCertPath string, ...) (RoundTripper, error)
- func CreateDefaultRoundTripperTls(ctx context.Context, caCertPath string, clientCertPath string, ...) (RoundTripper, error)deprecated
- func CreateRoundTripper(options ...RoundTripperOption) RoundTripper
- type RoundTripperFunc
- type RoundTripperMetrics
- type RoundTripperOption
- func WithDialKeepAlive(keepAlive time.Duration) RoundTripperOption
- func WithDialTimeout(timeout time.Duration) RoundTripperOption
- func WithExpectContinueTimeout(timeout time.Duration) RoundTripperOption
- func WithHTTP2(enabled bool) RoundTripperOption
- func WithIdleConnTimeout(timeout time.Duration) RoundTripperOption
- func WithLogging(enabled bool) RoundTripperOption
- func WithMaxIdleConns(n int) RoundTripperOption
- func WithProxy(proxy func(*http.Request) (*url.URL, error)) RoundTripperOption
- func WithResponseHeaderTimeout(timeout time.Duration) RoundTripperOption
- func WithRetry(count int, delay time.Duration) RoundTripperOption
- func WithTLSConfig(config *tls.Config) RoundTripperOption
- func WithTLSFiles(ctx context.Context, caCertPath, clientCertPath, clientKeyPath string) (RoundTripperOption, error)
- func WithTLSHandshakeTimeout(timeout time.Duration) RoundTripperOption
- func WithTimeouts(dial, tlsHandshake, responseHeader time.Duration) RoundTripperOption
- func WithoutProxy() RoundTripperOption
- func WithoutRetry() RoundTripperOption
- type RoundTripperOptions
- type ServerOptions
- type WithError
- func NewCPUProfileStartHandler() WithError
- func NewCPUProfileStopHandler() WithError
- func NewCpuProfileStartHandler() WithErrordeprecated
- func NewCpuProfileStopHandler() WithErrordeprecated
- func NewFileDownloader(path string) WithError
- func NewJSONHandler(jsonHandler JSONHandler) WithError
- func NewJSONHandlerUpdateTx(db libkv.DB, jsonHandler JSONHandlerTx) WithError
- func NewJSONHandlerViewTx(db libkv.DB, jsonHandler JSONHandlerTx) WithError
- func NewJsonHandler(jsonHandler JsonHandler) WithErrordeprecated
- func NewJsonHandlerUpdateTx(db libkv.DB, jsonHandler JsonHandlerTx) WithErrordeprecated
- func NewJsonHandlerViewTx(db libkv.DB, jsonHandler JsonHandlerTx) WithErrordeprecated
- func NewMemoryProfileDownloadHandler() WithError
- func NewMemoryProfileHandler() WithError
- func NewProfilingStart() WithError
- func NewProfilingStop() WithError
- type WithErrorFunc
- type WithErrorTx
- type WithErrorTxFunc
Constants ΒΆ
const ( // ApplicationJSONContentType is the MIME type for JSON responses. ApplicationJSONContentType = "application/json" // TextHTML is the MIME type for HTML responses. TextHTML = "text/html" // ApplicationJsonContentType is deprecated. Use ApplicationJSONContentType instead. // // Deprecated: Use ApplicationJSONContentType for correct Go naming conventions. // //nolint:revive ApplicationJsonContentType = ApplicationJSONContentType // TextHtml is deprecated. Use TextHTML instead. // // Deprecated: Use TextHTML for correct Go naming conventions. // //nolint:revive TextHtml = TextHTML )
const ( ErrorCodeValidation = "VALIDATION_ERROR" // 400 Bad Request ErrorCodeNotFound = "NOT_FOUND" // 404 Not Found ErrorCodeForbidden = "FORBIDDEN" // 403 Forbidden ErrorCodeInternal = "INTERNAL_ERROR" // 500 Internal Server Error )
Standard error codes for JSON error responses
const (
// ContentTypeHeaderName is the standard HTTP header name for content type.
ContentTypeHeaderName = "Content-Type"
)
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 ΒΆ
var ErrNotFound = stderrors.New("not found")
ErrNotFound is a sentinel error used to indicate that a requested resource was not found.
var ErrTooManyRedirects = stderrors.New("too many redirects")
ErrTooManyRedirects is a sentinel error indicating that the maximum number of redirects has been exceeded.
var NotFound = ErrNotFound
NotFound is deprecated. Use ErrNotFound instead.
Deprecated: Use ErrNotFound for correct Go error naming conventions (ST1012).
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 ΒΆ
CheckResponseIsSuccessful validates that an HTTP response indicates success. It returns ErrNotFound 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 ΒΆ added in v1.19.0
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 CreateDefaultHttpClient
deprecated
func CreateHTTPClient ΒΆ added in v1.19.0
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 CreateHTTPServer ΒΆ added in v1.19.0
func CreateHTTPServer( addr string, router http.Handler, serverOptions ServerOptions, ) *http.Server
CreateHTTPServer creates an HTTP server with the specified address, handler, and options.
func CreateHttpClient
deprecated
func CreateHttpServer
deprecated
added in
v1.18.0
func CreateTLSClientConfig ΒΆ added in v1.19.0
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 CreateTlsClientConfig
deprecated
func FileServer ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 NewDangerousHandlerWrapper ΒΆ added in v1.20.0
NewDangerousHandlerWrapper wraps dangerous HTTP handlers with passphrase protection. Each instance generates a unique passphrase that expires after 5 minutes. The passphrase is logged to stdout/stderr, requiring operators to have log access in addition to HTTP access to execute dangerous operations.
func NewDangerousHandlerWrapperWithCurrentDateTime ΒΆ added in v1.20.0
func NewDangerousHandlerWrapperWithCurrentDateTime( handler http.Handler, currentDateTime libtime.CurrentDateTime, ) http.Handler
NewDangerousHandlerWrapperWithCurrentDateTime wraps dangerous HTTP handlers with passphrase protection using the provided CurrentDateTime interface for testability.
func NewErrorHandler ΒΆ
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 NewJSONErrorHandler ΒΆ added in v1.24.0
NewJSONErrorHandler wraps a WithError handler to provide centralized JSON error handling. It converts errors to JSON responses with appropriate status codes and logs the results. If the error implements ErrorWithStatusCode, it uses that status code; otherwise defaults to 500. If the error implements ErrorWithCode, it uses that error code; otherwise defaults to INTERNAL_ERROR.
Example usage:
handler := libhttp.NewJSONErrorHandler(
libhttp.WithErrorFunc(func(ctx context.Context, resp http.ResponseWriter, req *http.Request) error {
return libhttp.WrapWithCode(
errors.New(ctx, "validation failed"),
libhttp.ErrorCodeValidation,
http.StatusBadRequest,
)
}),
)
func NewJSONUpdateErrorHandler ΒΆ added in v1.24.0
func NewJSONUpdateErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler
NewJSONUpdateErrorHandler wraps a WithErrorTx handler for update transactions, returning JSON error responses instead of plain text.
Example usage:
handler := libhttp.NewJSONUpdateErrorHandler(
db,
libhttp.WithErrorTxFunc(func(ctx context.Context, tx libkv.Tx, resp http.ResponseWriter, req *http.Request) error {
// Handle update logic with transaction
return nil
}),
)
func NewJSONViewErrorHandler ΒΆ added in v1.24.0
func NewJSONViewErrorHandler(db libkv.DB, withErrorTx WithErrorTx) http.Handler
NewJSONViewErrorHandler wraps a WithErrorTx handler for view (read-only) transactions, returning JSON error responses instead of plain text.
Example usage:
handler := libhttp.NewJSONViewErrorHandler(
db,
libhttp.WithErrorTxFunc(func(ctx context.Context, tx libkv.Tx, resp http.ResponseWriter, req *http.Request) error {
// Handle read-only logic with transaction
return nil
}),
)
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 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, optionFns ...func(serverOptions *ServerOptions), ) 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, optionFns ...func(serverOptions *ServerOptions), ) 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, optionFns ...func(serverOptions *ServerOptions), ) 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 ΒΆ
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 ΒΆ
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 SendJSONFileResponse ΒΆ added in v1.17.0
func SendJSONFileResponse( ctx context.Context, resp http.ResponseWriter, data interface{}, fileName string, statusCode int, ) error
SendJSONFileResponse writes a JSON-encoded response configured for file download. It sets Content-Type to application/json, adds a Content-Disposition header with the specified filename, and includes Content-Length for the response.
The filename must be a valid, safe filename (not a path). It will be validated and an error returned if it contains:
- Path separators or traversal sequences (/, \, ..)
- Control characters that could enable HTTP header injection
- Quotes that could break the header format
If you have a path and want to use just the filename, call filepath.Base() first.
Note: This function uses json.Marshal to buffer the entire response in memory, which is necessary to calculate and set the Content-Length header. For very large responses (>100MB), consider using streaming alternatives without Content-Length.
Example:
data := map[string]interface{}{"users": users}
err := http.SendJSONFileResponse(ctx, w, data, "users.json", http.StatusOK)
func SendJSONResponse ΒΆ added in v1.16.0
func SendJSONResponse( ctx context.Context, resp http.ResponseWriter, data interface{}, statusCode int, ) error
SendJSONResponse writes a JSON-encoded response with the specified status code. It sets the Content-Type header to application/json and returns any encoding errors.
func ValidateFilename ΒΆ added in v1.17.0
ValidateFilename checks if a filename is safe for use in Content-Disposition header. It returns an error if the filename:
- Is empty
- Contains path separators (/, \) or path traversal (..)
- Starts with a slash
- Contains control characters (ASCII 0-31, 127) that could enable header injection
- Contains quotes that could break the header format
- Is not clean according to filepath.Clean (catches sneaky path tricks)
This function expects a bare filename, not a path. If you have a path and want to extract the filename, use filepath.Base() first.
func WrapWithCode ΒΆ added in v1.24.0
WrapWithCode wraps an error with both an error code and HTTP status code. This allows the error to be used with JSON error handlers that return structured error responses.
Example:
err := WrapWithCode(
errors.New(ctx, "columnGroup '' is unknown"),
ErrorCodeValidation,
http.StatusBadRequest,
)
func WrapWithDetails ΒΆ added in v1.24.0
WrapWithDetails wraps an error with code, status, and structured details. This is a convenience helper that combines WrapWithCode with adding data to the error. Details can include any JSON-serializable values including arrays and nested objects.
Example:
err := WrapWithDetails(
errors.New(ctx, "columnGroup '' is unknown"),
ErrorCodeValidation,
http.StatusBadRequest,
map[string]any{
"field": "columnGroup",
"expected": []string{"day", "week", "month", "year"},
},
)
func WriteAndGlog ΒΆ
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
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 ΒΆ
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 ClientBuilder ΒΆ added in v1.19.0
type ClientBuilder interface {
WithRetry(retryLimit int, retryDelay time.Duration) ClientBuilder
WithoutRetry() ClientBuilder
WithProxy() ClientBuilder
WithoutProxy() ClientBuilder
// WithRedirects controls how many redirects are allowed
// 0 = no redirects, -1 = infinit redirects, 10 = 10 max redirects
WithRedirects(maxRedirect int) ClientBuilder
// WithoutRedirects is equal to WithRedirects(0)
WithoutRedirects() ClientBuilder
WithTimeout(timeout time.Duration) ClientBuilder
WithDialFunc(dialFunc DialFunc) ClientBuilder
WithInsecureSkipVerify(insecureSkipVerify bool) ClientBuilder
WithClientCert(caCertPath string, clientCertPath string, clientKeyPath string) ClientBuilder
Build(ctx context.Context) (*http.Client, error)
BuildRoundTripper(ctx context.Context) (http.RoundTripper, error)
}
ClientBuilder 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() ClientBuilder
NewClientBuilder creates a new HTTP client builder with sensible defaults. Default configuration includes: no proxy, max 10 redirects, 30 second timeout, no retry.
type DialFunc ΒΆ
DialFunc defines a function that establishes network connections. It should return a connection to the given network address.
type ErrorDetails ΒΆ added in v1.24.0
type ErrorDetails struct {
// Code is the error type identifier (e.g., VALIDATION_ERROR, NOT_FOUND)
Code string `json:"code"`
// Message is the human-readable error message
Message string `json:"message"`
// Details contains optional structured data extracted from errors.HasData interface.
// Supports any JSON-serializable values including arrays and nested objects.
// Omitted from JSON if nil or empty.
Details map[string]any `json:"details,omitempty"`
}
ErrorDetails contains structured error information for client responses.
type ErrorResponse ΒΆ added in v1.24.0
type ErrorResponse struct {
Error ErrorDetails `json:"error"`
}
ErrorResponse wraps error details in standard JSON format. It provides a consistent structure for error responses across HTTP services.
Example JSON output:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "columnGroup '' is unknown",
"details": {
"field": "columnGroup",
"expected": "day|week|month|year"
}
}
}
type ErrorWithCode ΒΆ added in v1.24.0
ErrorWithCode defines an error that can provide a typed error code. This interface allows errors to specify an error code (e.g., VALIDATION_ERROR, NOT_FOUND) for structured JSON error responses.
type ErrorWithStatusCode ΒΆ added in v1.9.0
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 HTTPClientBuilder
deprecated
added in
v1.19.0
type HTTPClientBuilder = ClientBuilder
HTTPClientBuilder is deprecated. Use ClientBuilder instead.
Deprecated: Use ClientBuilder to avoid package name stuttering.
type Handler ΒΆ added in v1.11.0
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
deprecated
type HttpClientBuilder = ClientBuilder
HttpClientBuilder is deprecated. Use ClientBuilder instead.
Deprecated: Use ClientBuilder for correct Go naming conventions and to avoid package name stuttering.
type JSONHandler ΒΆ added in v1.19.0
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 ΒΆ added in v1.19.0
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.
type JSONHandlerTx ΒΆ added in v1.19.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.19.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.
type JsonHandler
deprecated
type JsonHandler = JSONHandler
JsonHandler is deprecated. Use JSONHandler instead.
Deprecated: Use JSONHandler for correct Go naming conventions.
type JsonHandlerFunc
deprecated
type JsonHandlerFunc = JSONHandlerFunc
JsonHandlerFunc is deprecated. Use JSONHandlerFunc instead.
Deprecated: Use JSONHandlerFunc for correct Go naming conventions.
type JsonHandlerTx
deprecated
added in
v1.8.0
type JsonHandlerTx = JSONHandlerTx
JsonHandlerTx is deprecated. Use JSONHandlerTx instead.
Deprecated: Use JSONHandlerTx for correct Go naming conventions.
type JsonHandlerTxFunc
deprecated
added in
v1.8.0
type JsonHandlerTxFunc = JSONHandlerTxFunc
JsonHandlerTxFunc is deprecated. Use JSONHandlerTxFunc instead.
Deprecated: Use JSONHandlerTxFunc for correct Go naming conventions.
type Proxy ΒΆ
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 ΒΆ
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 ΒΆ added in v1.19.0
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.
func CreateDefaultRoundTripperTls
deprecated
func CreateDefaultRoundTripperTls( ctx context.Context, caCertPath string, clientCertPath string, clientKeyPath string, ) (RoundTripper, error)
CreateDefaultRoundTripperTls is deprecated. Use CreateDefaultRoundTripperTLS instead.
Deprecated: Use CreateDefaultRoundTripperTLS for correct Go naming conventions.
func CreateRoundTripper ΒΆ added in v1.23.0
func CreateRoundTripper(options ...RoundTripperOption) RoundTripper
CreateRoundTripper creates a RoundTripper with the specified options. If no options are provided, sensible defaults are used.
Default configuration:
- Retry: 5 attempts with 1 second delay
- Logging: enabled
- HTTP/2: enabled
- Timeouts: 30s dial, 10s TLS handshake, 30s response headers
- Max idle connections: 100
- Idle timeout: 90s
- Proxy: from environment variables
type RoundTripperFunc ΒΆ
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.
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 RoundTripperOption ΒΆ added in v1.23.0
type RoundTripperOption func(*RoundTripperOptions)
RoundTripperOption defines a function type for modifying RoundTripper configuration.
func WithDialKeepAlive ΒΆ added in v1.23.0
func WithDialKeepAlive(keepAlive time.Duration) RoundTripperOption
WithDialKeepAlive sets the keep-alive period for active connections.
func WithDialTimeout ΒΆ added in v1.23.0
func WithDialTimeout(timeout time.Duration) RoundTripperOption
WithDialTimeout sets the timeout for establishing connections.
func WithExpectContinueTimeout ΒΆ added in v1.23.0
func WithExpectContinueTimeout(timeout time.Duration) RoundTripperOption
WithExpectContinueTimeout sets the timeout for Expect: 100-continue responses.
func WithHTTP2 ΒΆ added in v1.23.0
func WithHTTP2(enabled bool) RoundTripperOption
WithHTTP2 enables or disables HTTP/2.
func WithIdleConnTimeout ΒΆ added in v1.23.0
func WithIdleConnTimeout(timeout time.Duration) RoundTripperOption
WithIdleConnTimeout sets the timeout for idle connections.
func WithLogging ΒΆ added in v1.23.0
func WithLogging(enabled bool) RoundTripperOption
WithLogging enables or disables request/response logging.
func WithMaxIdleConns ΒΆ added in v1.23.0
func WithMaxIdleConns(n int) RoundTripperOption
WithMaxIdleConns sets the maximum number of idle connections.
func WithResponseHeaderTimeout ΒΆ added in v1.23.0
func WithResponseHeaderTimeout(timeout time.Duration) RoundTripperOption
WithResponseHeaderTimeout sets the timeout for reading response headers.
func WithRetry ΒΆ added in v1.23.0
func WithRetry(count int, delay time.Duration) RoundTripperOption
WithRetry configures retry behavior. Set count to 0 to disable retries.
func WithTLSConfig ΒΆ added in v1.23.0
func WithTLSConfig(config *tls.Config) RoundTripperOption
WithTLSConfig sets the TLS configuration for client certificates and server verification.
func WithTLSFiles ΒΆ added in v1.23.0
func WithTLSFiles( ctx context.Context, caCertPath, clientCertPath, clientKeyPath string, ) (RoundTripperOption, error)
WithTLSFiles loads TLS configuration from certificate files. It loads the specified CA certificate, client certificate, and private key for mutual TLS authentication.
func WithTLSHandshakeTimeout ΒΆ added in v1.23.0
func WithTLSHandshakeTimeout(timeout time.Duration) RoundTripperOption
WithTLSHandshakeTimeout sets the timeout for TLS handshakes.
func WithTimeouts ΒΆ added in v1.23.0
func WithTimeouts(dial, tlsHandshake, responseHeader time.Duration) RoundTripperOption
WithTimeouts sets all timeout values at once for convenience.
func WithoutProxy ΒΆ added in v1.23.0
func WithoutProxy() RoundTripperOption
WithoutProxy disables proxy usage.
func WithoutRetry ΒΆ added in v1.23.0
func WithoutRetry() RoundTripperOption
WithoutRetry disables retry logic.
type RoundTripperOptions ΒΆ added in v1.23.0
type RoundTripperOptions struct {
// TLS configuration for client certificates and server verification
TLSConfig *tls.Config
// Retry configuration
RetryCount int
RetryDelay time.Duration
// Transport settings
DialTimeout time.Duration
DialKeepAlive time.Duration
ForceAttemptHTTP2 bool
MaxIdleConns int
IdleConnTimeout time.Duration
TLSHandshakeTimeout time.Duration
ExpectContinueTimeout time.Duration
ResponseHeaderTimeout time.Duration
// Proxy configuration
Proxy func(*http.Request) (*url.URL, error)
// Enable request/response logging
EnableLogging bool
}
RoundTripperOptions holds all optional configuration for RoundTripper.
type ServerOptions ΒΆ added in v1.18.0
type ServerOptions struct {
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
ShutdownTimeout time.Duration
MaxHeaderBytes int
TLSConfig *tls.Config
CertFile string
KeyFile string
}
ServerOptions configures HTTP server behavior. ReadHeaderTimeout sets the maximum duration for reading request headers (Slowloris protection). ReadTimeout sets the maximum duration for reading the entire request (headers + body). WriteTimeout sets the maximum duration for writing the response. IdleTimeout sets the maximum duration to wait for the next request when keep-alives are enabled. ShutdownTimeout sets the maximum duration to wait for graceful shutdown. MaxHeaderBytes limits the size of request headers to prevent memory exhaustion attacks. TLSConfig provides custom TLS configuration for HTTPS servers. CertFile and KeyFile specify paths to TLS certificate and private key files for HTTPS.
func CreateServerOptions ΒΆ added in v1.18.0
func CreateServerOptions(optionFns ...func(serverOptions *ServerOptions)) ServerOptions
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 ΒΆ added in v1.19.0
func NewCPUProfileStartHandler() WithError
NewCPUProfileStartHandler creates a handler that starts CPU profiling. The profile is written to cpu.pprof in the current directory.
func NewCPUProfileStopHandler ΒΆ added in v1.19.0
func NewCPUProfileStopHandler() WithError
NewCPUProfileStopHandler creates a handler that stops CPU profiling.
func NewCpuProfileStartHandler
deprecated
func NewCpuProfileStartHandler() WithError
NewCpuProfileStartHandler is deprecated. Use NewCPUProfileStartHandler instead.
Deprecated: Use NewCPUProfileStartHandler for correct Go naming conventions.
func NewCpuProfileStopHandler
deprecated
func NewCpuProfileStopHandler() WithError
NewCpuProfileStopHandler is deprecated. Use NewCPUProfileStopHandler instead.
Deprecated: Use NewCPUProfileStopHandler for correct Go naming conventions.
func NewFileDownloader ΒΆ
func NewJSONHandler ΒΆ added in v1.19.0
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.19.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.19.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 NewJsonHandler
deprecated
func NewJsonHandler(jsonHandler JsonHandler) WithError
NewJsonHandler is deprecated. Use NewJSONHandler instead.
Deprecated: Use NewJSONHandler for correct Go naming conventions.
func NewJsonHandlerUpdateTx
deprecated
added in
v1.8.0
func NewJsonHandlerUpdateTx(db libkv.DB, jsonHandler JsonHandlerTx) WithError
NewJsonHandlerUpdateTx is deprecated. Use NewJSONHandlerUpdateTx instead.
Deprecated: Use NewJSONHandlerUpdateTx for correct Go naming conventions.
func NewJsonHandlerViewTx
deprecated
added in
v1.8.0
func NewJsonHandlerViewTx(db libkv.DB, jsonHandler JsonHandlerTx) WithError
NewJsonHandlerViewTx is deprecated. Use NewJSONHandlerViewTx instead.
Deprecated: Use NewJSONHandlerViewTx for correct Go naming conventions.
func NewMemoryProfileDownloadHandler ΒΆ added in v1.22.0
func NewMemoryProfileDownloadHandler() WithError
NewMemoryProfileDownloadHandler creates a handler that generates a memory profile and sends it as a downloadable file to the client. The profile is streamed directly to the HTTP response without buffering in memory to avoid additional memory pressure on the service.
func NewMemoryProfileHandler ΒΆ
func NewMemoryProfileHandler() WithError
NewMemoryProfileHandler creates a handler that writes a memory profile to a local file. The profile is saved to "memprofile.pprof" in the current working directory. On success, it writes a confirmation message to the HTTP response.
func NewProfilingStart ΒΆ
func NewProfilingStart() WithError
func NewProfilingStop ΒΆ
func NewProfilingStop() WithError
type WithErrorFunc ΒΆ
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.
Source Files
ΒΆ
- doc.go
- http_background-handler.go
- http_background-request-handler.go
- http_build-request.go
- http_check-response.go
- http_client-builder.go
- http_client.go
- http_content-types.go
- http_cpu-profile-handler.go
- http_dangerous-handler.go
- http_error-handler-tx.go
- http_error-handler.go
- http_error-response.go
- http_errors.go
- http_file-downloader-handler.go
- http_fileserver.go
- http_garbage-collector-handler.go
- http_handler-func.go
- http_handler.go
- http_headers.go
- http_json-error-handler-tx.go
- http_json-error-handler.go
- http_json-handler-tx.go
- http_json-handler.go
- http_memory-profile-handler.go
- http_pprof-handler.go
- http_pprof.go
- http_print-handler.go
- http_proxy-error-handler-sentry.go
- http_proxy-error-handler.go
- http_proxy.go
- http_roundtripper-basic-auth.go
- http_roundtripper-default.go
- http_roundtripper-func.go
- http_roundtripper-header.go
- http_roundtripper-log.go
- http_roundtripper-options.go
- http_roundtripper-ratelimit.go
- http_roundtripper-remove-path-prefix.go
- http_roundtripper-retry.go
- http_roundtripper.go
- http_roundtripper_metrics.go
- http_send-json-response.go
- http_server.go
- http_with-error-tx.go
- http_with-error.go
- http_write-and-glog.go