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 CreateHttpClient(timeout time.Duration) *http.Client
- func CreateTlsClientConfig(ctx context.Context, caCertPath string, clientCertPath string, ...) (*tls.Config, error)
- 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 NewErrorHandler(withError WithError) http.Handler
- func NewGarbageCollectorHandler() 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) 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 WriteAndGlog(w io.Writer, format string, a ...any) (n int, err error)
- type BackgroundRunRequestFunc
- type CheckRedirect
- type DialFunc
- type ErrorWithStatusCode
- type Handler
- type HandlerFunc
- type HasTemporaryError
- type HasTimeoutError
- type HttpClientBuilder
- type JsonHandler
- type JsonHandlerFunc
- type JsonHandlerTx
- type JsonHandlerTxFunc
- type Proxy
- type ProxyErrorHandler
- type ProxyErrorHandlerFunc
- type RequestFailedError
- type RoundTripper
- type RoundTripperFunc
- type RoundTripperMetrics
- type WithError
- func NewCpuProfileStartHandler() WithError
- func NewCpuProfileStopHandler() WithError
- 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 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" )
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 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 ΒΆ
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 ΒΆ
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 ΒΆ
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 ΒΆ
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 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 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 ΒΆ
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 ΒΆ
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 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 DialFunc ΒΆ
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
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
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 ΒΆ
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.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.
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 ΒΆ
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 ΒΆ
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 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 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 ΒΆ
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_error-handler-tx.go
- http_error-handler.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-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-ratelimit.go
- http_roundtripper-remove-path-prefix.go
- http_roundtripper-retry.go
- http_roundtripper.go
- http_roundtripper_metrics.go
- http_server.go
- http_with-error-tx.go
- http_with-error.go
- http_write-and-glog.go