Documentation
¶
Overview ¶
Package webhandler provides a suite of handlers, middleware, and utilities for web applications. It streamlines common tasks such as request logging, generating unique request IDs, and rendering HTML templates.
Index ¶
- func AddSecurityHeaders(next http.Handler) http.Handler
- func FileHandler(path string) http.HandlerFunc
- func FilesFromDir(urlPrefix, dir string) http.HandlerFunc
- func LogRequest(next http.Handler) http.Handler
- func Logger(ctx context.Context) *slog.Logger
- func MiddlewareLogger(next http.Handler) http.Handler
- func NewRequestIDMiddleware(next http.Handler) http.Handler
- func RemoteGetHandler(w http.ResponseWriter, r *http.Request)
- func RequestGetHandler(w http.ResponseWriter, r *http.Request)
- func RequestID(ctx context.Context) string
- func RequestLogger(r *http.Request) *slog.Logger
- func RequestLoggerWithFuncName(r *http.Request) *slog.Logger
- func TestHandler(t *testing.T, handlerFunc http.HandlerFunc, testCases []TestCase)
- type TestCase
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddSecurityHeaders ¶
AddSecurityHeaders returns middleware that applies essential security headers to HTTP responses to enhance web application security.
It sets the following headers:
- Content-Security-Policy: Restricts sources for default resource loading to the same origin and explicitly allows inline styles, helping prevent XSS attacks.
- X-Content-Type-Options: Disables MIME type sniffing and enforces the MIME types specified in Content-Type headers to mitigate MIME type confusion attacks.
- X-Frame-Options: Prohibits embedding the content in frames, safeguarding against clickjacking.
- X-XSS-Protection: Enables browser-side XSS filters and configures them to block detected XSS attacks.
func FileHandler ¶
func FileHandler(path string) http.HandlerFunc
FileHandler returns an http.HandlerFunc that serves the single file at path. If the file does not exist or cannot be accessed at startup, the returned handler always responds with 404 Not Found and logs the error once.
Typical use is to serve a static page such as /robots.txt or /favicon.ico.
func FilesFromDir ¶
func FilesFromDir(urlPrefix, dir string) http.HandlerFunc
FilesFromDir returns an http.HandlerFunc that serves files from dir at the given urlPrefix (e.g., "/css/"), rejecting direct directory requests.
The returned handler:
- Strips urlPrefix from the request path to map to the file under dir.
- Responds 404 if the request points to a directory (ends with "/").
- Uses http.ServeFile so content type, caching headers, and range requests work as usual.
Example:
mux.Handle("/css/", FilesFromDir("/css/", "assets/css"))
func LogRequest ¶
LogRequest creates a middleware function that logs the start and completion of each HTTP request, including the duration and status code.
func Logger ¶
Logger attempts to retrieve a logger from the provided context.
It returns the default logger if context is nil or does not contain a logger.
func MiddlewareLogger ¶
MiddlewareLogger creates middleware that injects a logger into the request context, enabling subsequent handlers in the chain to log request-specific information.
func NewRequestIDMiddleware ¶
NewRequestIDMiddleware creates middleware that assigns a unique request ID to every incoming HTTP request. This ID is added to the request's context and set as the 'X-Request-ID' header in the HTTP response.
It uses an atomic counter to ensure each ID is unique across all requests.
func RemoteGetHandler ¶
func RemoteGetHandler(w http.ResponseWriter, r *http.Request)
RemoteGetHandler responds with the requesting client's RemoteAddr and potentially real IP addresses from common headers used by proxies or load balancers.
This handler ensures that it only responds to HTTP GET requests and includes headers to prevent response caching.
func RequestGetHandler ¶
func RequestGetHandler(w http.ResponseWriter, r *http.Request)
RequestGetHandler serves as an HTTP handler that responds by providing a detailed dump of the incoming HTTP request.
func RequestID ¶
RequestID extracts the request ID from the provided context.
If the context is nil or does not include a request ID, the function returns an empty string.
func RequestLogger ¶
RequestLogger creates and configures a logger specifically for logging HTTP request details, such as the method, URL, and client IP. It optionally includes a request ID if present.
func RequestLoggerWithFuncName ¶
RequestLoggerWithFuncName augments a request logger by adding the caller function's name to the log attributes.
func TestHandler ¶
func TestHandler(t *testing.T, handlerFunc http.HandlerFunc, testCases []TestCase)
TestHandler tests an HTTP handler with a slice of test cases. It automates sending requests and comparing expected to actual outcomes.
Types ¶
type TestCase ¶
type TestCase struct {
Name string // Test case name.
Target string // Request target URL.
RequestMethod string // HTTP method.
RequestHeaders http.Header // Headers to include in request.
RequestCookies []http.Cookie // Cookies to include in request.
RequestBody string // Request body content.
WantStatus int // Expected HTTP status code.
WantBody string // Expected response body.
WantCookies []http.Cookie // Expected cookies in response.
WantCookiesCmpOpts cmp.Options // Comparison options for cookies.
}
TestCase defines a structure for parameters and expected results for handler tests.