httpx

package
v0.0.0-...-ccee039 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultReadHeaderTimeout = 10 * time.Second
	DefaultReadTimeout       = 30 * time.Second
	DefaultWriteTimeout      = 30 * time.Second
	DefaultIdleTimeout       = 120 * time.Second
)
View Source
const DefaultFlashCookieName = "flash"

DefaultFlashCookieName is used when [Flash.CookieName] is empty.

Variables

This section is empty.

Functions

func DecodeJSON

func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool

DecodeJSON reads a JSON request body into dst. Returns false and writes a 400 error if decoding fails.

func GetRenderTime

func GetRenderTime(ctx context.Context) string

GetRenderTime returns the elapsed time since the request started, as a rounded duration string. Returns "" if WithRenderInfo was not installed.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context, or empty string.

func RespondError

func RespondError(w http.ResponseWriter, status int, message, code string)

RespondError writes a JSON error response.

func RespondJSON

func RespondJSON(w http.ResponseWriter, status int, data any)

RespondJSON writes a JSON response with the given status code.

func SecurityHeaders

func SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders adds standard security headers to every response.

func WithRenderInfo

func WithRenderInfo(next http.Handler) http.Handler

WithRenderInfo attaches a RenderInfo to the request context.

func WithRequestID

func WithRequestID(next http.Handler) http.Handler

WithRequestID adds a unique request ID to each request. If the request already has an X-Request-ID header (e.g. from a load balancer), it is reused. The ID is also stored on the context and retrievable via GetRequestID.

func WithSignalShutdown

func WithSignalShutdown(ctx context.Context, logger *slog.Logger) (context.Context, context.CancelFunc)

WithSignalShutdown returns a context that is cancelled on SIGINT or SIGTERM.

Types

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
	Code  string `json:"code,omitempty"`
}

ErrorResponse is a standard JSON error format.

type Flash

type Flash struct {
	// CookieName overrides the cookie name. Empty uses DefaultFlashCookieName.
	CookieName string
}

Flash reads and writes one-shot feedback messages via cookie.

func (*Flash) Get

Get retrieves and clears the flash cookie. Returns nil if no flash is set.

func (*Flash) Middleware

func (f *Flash) Middleware(key any) func(http.Handler) http.Handler

Middleware loads any flash message into the request context under key, clearing the cookie. Handlers retrieve it via a caller-owned helper.

func (*Flash) Set

func (f *Flash) Set(w http.ResponseWriter, kind, message string)

Set stores a flash message. The message is consumed on the next request by Get.

type FlashMessage

type FlashMessage struct {
	Type    string `json:"type"` // "success", "error", "warning", "info"
	Message string `json:"message"`
}

FlashMessage represents a one-time feedback message displayed after a redirect (e.g. "File uploaded successfully").

type IPResolver

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

IPResolver extracts the originating client IP from a request, honoring X-Forwarded-For only when the immediate peer (and any intermediate hops) fall within a configured set of trusted proxy ranges. Defaults to loopback only — clients connecting from anywhere else are taken at face value via RemoteAddr, ignoring forwarded headers.

func NewIPResolver

func NewIPResolver(trusted []netip.Prefix) *IPResolver

NewIPResolver creates a resolver. If trusted is empty, only loopback (127.0.0.0/8 and ::1) is treated as trusted.

func (*IPResolver) ClientIP

func (ir *IPResolver) ClientIP(r *http.Request) string

ClientIP returns the originating client IP for r. If the request's immediate peer is a trusted proxy, X-Forwarded-For is walked right-to-left and the first untrusted address is returned. Otherwise RemoteAddr is used.

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware is the standard middleware signature.

func ByMethod

func ByMethod(read, write Middleware, extraReadMethods ...string) Middleware

ByMethod returns middleware that dispatches to read for safe methods (GET, HEAD, OPTIONS, plus any extraReadMethods such as "PROPFIND") and write for everything else. Either middleware may be nil to skip wrapping for that side.

Use this to apply different gates to read vs. write paths on a single route — e.g. requiring "files:read" scope for GET and "files:write" for POST/PUT/DELETE.

func CSP

func CSP(policy string) Middleware

CSP returns middleware that sets a Content-Security-Policy header on every response. The policy is application-specific; callers pass it in directly (e.g. "default-src 'self'; script-src 'self'").

func Logging

func Logging(logger *slog.Logger) Middleware

Logging creates middleware that logs each request with method, path, status, duration, and bytes written. It attaches a child logger with the request ID to the context.

func Recovery

func Recovery(logger *slog.Logger) Middleware

Recovery creates middleware that recovers from panics, logs the error and stack trace, and returns 500.

type RenderInfo

type RenderInfo struct {
	GoVersion  string
	AppVersion string
	StartTime  time.Time
}

RenderInfo carries metadata used by templates to display build and timing details (Go version, app version, request start time).

func GetRenderInfo

func GetRenderInfo(ctx context.Context) *RenderInfo

GetRenderInfo returns the RenderInfo from ctx, or nil if the middleware was not installed.

type Router

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

Router wraps http.ServeMux with middleware support and route grouping.

func NewRouter

func NewRouter(logger *slog.Logger) *Router

NewRouter creates a Router with optional middleware already applied.

func (*Router) Group

func (r *Router) Group(fn func(*Router))

Group creates a sub-router that inherits the current middleware stack. Additional middleware or routes added inside the callback do not affect the parent.

func (*Router) Handle

func (r *Router) Handle(pattern string, handler http.HandlerFunc)

Handle registers a handler for the given pattern with all active middleware applied.

func (*Router) ListenAndServe

func (r *Router) ListenAndServe(ctx context.Context, bind string) error

ListenAndServe starts the HTTP server. It supports both TCP ("host:port") and Unix socket ("unix:/path/to/socket") bind addresses. The server shuts down gracefully when ctx is cancelled.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler.

func (*Router) Use

func (r *Router) Use(middlewares ...Middleware)

Use appends middleware to the stack. Middleware added here applies to all routes registered after this call (and within this group).

Jump to

Keyboard shortcuts

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