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(name 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 NewRequestLogger(r *http.Request) *slog.Logger
- func NewRequestLoggerWithFuncName(r *http.Request) *slog.Logger
- func RemoteGetHandler(w http.ResponseWriter, r *http.Request)
- func RequestGetHandler(w http.ResponseWriter, r *http.Request)
- func RequestID(ctx context.Context) string
- 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(name string) http.HandlerFunc
FileHandler returns a HTTP handler that serves a specified file from the provided name. This handler uses http.ServeFile to serve the file directly.
If the file specified by name does not exist or is not accessible, the handler logs the error and returns an HTTP 404 (Not Found) response for all incoming requests.
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 NewRequestLogger ¶
NewRequestLogger 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 NewRequestLoggerWithFuncName ¶
NewRequestLoggerWithFuncName augments a request logger by adding the caller function's name to the log attributes.
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 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.