Thanks to visit codestin.com
Credit goes to pkg.go.dev

http

package module
v1.26.0 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: BSD-2-Clause Imports: 38 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)
}
JSON Error Handler

The JSON error handler returns structured error responses in JSON format instead of plain text, making errors easier to parse and handle programmatically.

type ErrorResponse struct {
    Message string `json:"message"`
}

func apiHandler(ctx context.Context, resp http.ResponseWriter, req *http.Request) error {
    // Return an error with status code
    return bhttp.WrapWithCode(
        errors.New(ctx, "validation failed"),
        bhttp.ErrorCodeValidation,
        http.StatusBadRequest,
    )
}

func main() {
    router := mux.NewRouter()

    // JSON error handler returns structured JSON error responses
    handler := bhttp.NewJSONErrorHandler(
        bhttp.WithErrorFunc(apiHandler),
    )

    router.Handle("/api/resource", handler)

    server := bhttp.NewServerWithPort(8080, router)
    run.CancelOnInterrupt(context.Background(), server)
}

Error Response Format:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "validation failed",
    "details": {
      "field": "email",
      "reason": "invalid_format"
    }
  }
}

Available Error Codes:

  • ErrorCodeValidation - For validation errors (400)
  • ErrorCodeNotFound - For not found errors (404)
  • ErrorCodeUnauthorized - For authentication errors (401)
  • ErrorCodeForbidden - For authorization errors (403)
  • ErrorCodeInternal - For internal server errors (500)

With Error Details:

// Add structured details to errors
return bhttp.WrapWithDetails(
    errors.New(ctx, "validation failed"),
    bhttp.ErrorCodeValidation,
    http.StatusBadRequest,
    map[string]string{
        "field": "email",
        "reason": "invalid_format",
    },
)

With Database Transactions:

// For update operations
handler := bhttp.NewJSONUpdateErrorHandler(db,
    bhttp.WithErrorTxFunc(func(ctx context.Context, tx libkv.Tx, resp http.ResponseWriter, req *http.Request) error {
        // Handle update logic with transaction
        return nil
    }),
)

// For read-only operations
handler := bhttp.NewJSONViewErrorHandler(db,
    bhttp.WithErrorTxFunc(func(ctx context.Context, tx libkv.Tx, resp http.ResponseWriter, req *http.Request) error {
        // Handle read logic with transaction
        return nil
    }),
)
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"

	// 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
)
View Source
const (
	ErrorCodeValidation   = "VALIDATION_ERROR" // 400 Bad Request
	ErrorCodeNotFound     = "NOT_FOUND"        // 404 Not Found
	ErrorCodeUnauthorized = "UNAUTHORIZED"     // 401 Unauthorized
	ErrorCodeForbidden    = "FORBIDDEN"        // 403 Forbidden
	ErrorCodeInternal     = "INTERNAL_ERROR"   // 500 Internal Server Error
)

Standard error codes for JSON error responses

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 ErrNotFound = stderrors.New("not found")

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

View Source
var ErrTooManyRedirects = stderrors.New("too many redirects")

ErrTooManyRedirects is a sentinel error indicating that the maximum number of redirects has been exceeded.

View Source
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 ΒΆ

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

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

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 CreateDefaultHttpClient deprecated

func CreateDefaultHttpClient() *http.Client

CreateDefaultHttpClient is deprecated. Use CreateDefaultHTTPClient instead.

Deprecated: Use CreateDefaultHTTPClient for correct Go naming conventions.

func CreateHTTPClient ΒΆ added in v1.19.0

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 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 CreateHttpClient(timeout time.Duration) *http.Client

CreateHttpClient is deprecated. Use CreateHTTPClient instead.

Deprecated: Use CreateHTTPClient for correct Go naming conventions.

func CreateHttpServer deprecated added in v1.18.0

func CreateHttpServer(
	addr string,
	router http.Handler,
	serverOptions ServerOptions,
) *http.Server

CreateHttpServer is deprecated. Use CreateHTTPServer instead.

Deprecated: Use CreateHTTPServer for correct Go naming conventions.

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 CreateTlsClientConfig(
	ctx context.Context,
	caCertPath string,
	clientCertPath string,
	clientKeyPath string,
) (*tls.Config, error)

CreateTlsClientConfig is deprecated. Use CreateTLSClientConfig instead.

Deprecated: Use CreateTLSClientConfig for correct Go naming conventions.

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 NewDangerousHandlerWrapper ΒΆ added in v1.20.0

func NewDangerousHandlerWrapper(handler http.Handler) http.Handler

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 ΒΆ

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 NewJSONErrorHandler ΒΆ added in v1.24.0

func NewJSONErrorHandler(withError WithError) http.Handler

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 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,
	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 ΒΆ

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 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

func ValidateFilename(ctx context.Context, name string) error

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

func WrapWithCode(err error, code string, statusCode int) error

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

func WrapWithDetails(err error, code string, statusCode int, details map[string]any) error

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 ΒΆ

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 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 ΒΆ

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 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

type ErrorWithCode interface {
	error
	Code() string
}

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

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 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

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 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

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 ΒΆ added in v1.19.0

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

ServeHTTP calls f(ctx, req).

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.

func (JSONHandlerTxFunc) ServeHTTP ΒΆ added in v1.19.0

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

ServeHTTP calls f(ctx, tx, req).

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 ΒΆ

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 ΒΆ 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 ΒΆ

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 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 WithProxy ΒΆ added in v1.23.0

func WithProxy(proxy func(*http.Request) (*url.URL, error)) RoundTripperOption

WithProxy sets a custom proxy function.

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 NewFileDownloader(path string) WithError

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 ΒΆ

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