Documentation
¶
Index ¶
- Constants
- func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool
- func GetRenderTime(ctx context.Context) string
- func GetRequestID(ctx context.Context) string
- func RespondError(w http.ResponseWriter, status int, message, code string)
- func RespondJSON(w http.ResponseWriter, status int, data any)
- func SecurityHeaders(next http.Handler) http.Handler
- func WithRenderInfo(next http.Handler) http.Handler
- func WithRequestID(next http.Handler) http.Handler
- func WithSignalShutdown(ctx context.Context, logger *slog.Logger) (context.Context, context.CancelFunc)
- type ErrorResponse
- type Flash
- type FlashMessage
- type IPResolver
- type Middleware
- type RenderInfo
- type Router
Constants ¶
const ( DefaultReadHeaderTimeout = 10 * time.Second DefaultReadTimeout = 30 * time.Second DefaultWriteTimeout = 30 * time.Second DefaultIdleTimeout = 120 * time.Second )
const DefaultFlashCookieName = "flash"
DefaultFlashCookieName is used when [Flash.CookieName] is empty.
Variables ¶
This section is empty.
Functions ¶
func DecodeJSON ¶
DecodeJSON reads a JSON request body into dst. Returns false and writes a 400 error if decoding fails.
func GetRenderTime ¶
GetRenderTime returns the elapsed time since the request started, as a rounded duration string. Returns "" if WithRenderInfo was not installed.
func GetRequestID ¶
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 ¶
SecurityHeaders adds standard security headers to every response.
func WithRenderInfo ¶
WithRenderInfo attaches a RenderInfo to the request context.
func WithRequestID ¶
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 ¶
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 ¶
func (f *Flash) Get(w http.ResponseWriter, r *http.Request) *FlashMessage
Get retrieves and clears the flash cookie. Returns nil if no flash is set.
func (*Flash) Middleware ¶
Middleware loads any flash message into the request context under key, clearing the cookie. Handlers retrieve it via a caller-owned helper.
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 ¶
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 ¶
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 (*Router) Group ¶
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 ¶
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).