Documentation
¶
Overview ¶
Package httputil provides shared HTTP server primitives used across graycode-router's API surfaces. Centralizing these eliminates drift in auth comparison, body decoding, JSON responses, security headers, and loopback validation that previously existed as duplicated copies in internal/api/server.go and other handlers.
Index ¶
- Constants
- func ConstantTimeEqual(a, b string) bool
- func DecodeJSONBody(w http.ResponseWriter, r *http.Request, dst any) bool
- func DecodeJSONBodyWithLimit(w http.ResponseWriter, r *http.Request, dst any, maxBytes int64) bool
- func ExtractBearerToken(r *http.Request) string
- func IsLoopbackHost(host string) bool
- func SecurityHeaders(next http.Handler) http.Handler
- func ValidateAuthConfig(addr, apiKey string) error
- func WriteJSON(w http.ResponseWriter, status int, v interface{})
Constants ¶
const MaxRequestBodyBytes = 1 << 20
MaxRequestBodyBytes is the default maximum request body size (1 MiB).
Variables ¶
This section is empty.
Functions ¶
func ConstantTimeEqual ¶
ConstantTimeEqual compares two strings in constant time. The shorter value is padded with NUL bytes so comparison time does not leak token length. This is the preferred bearer-token comparison for API servers.
func DecodeJSONBody ¶
DecodeJSONBody decodes a JSON request body into dst with a size limit and strict unknown-field rejection. Returns true on success. On failure it writes a 400 JSON error response and returns false.
func DecodeJSONBodyWithLimit ¶
DecodeJSONBodyWithLimit is like DecodeJSONBody but with a custom body size limit.
func ExtractBearerToken ¶
ExtractBearerToken extracts a bearer/API-key token from request headers. It checks "Authorization: Bearer ..." first, then "X-API-Key". The Bearer scheme is matched case-insensitively per RFC 7235.
func IsLoopbackHost ¶
IsLoopbackHost reports whether host is a loopback address: 127.0.0.0/8, ::1, or "localhost". An empty string is treated as non-loopback (fail-safe).
func SecurityHeaders ¶
SecurityHeaders wraps an http.Handler with standard security headers (X-Content-Type-Options, X-Frame-Options, Cache-Control).
func ValidateAuthConfig ¶
ValidateAuthConfig refuses to start a server with no API key on a non-loopback bind. Returns nil if the API key is set or the bind address is loopback.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, v interface{})
WriteJSON writes a JSON response with the given status code.
Types ¶
This section is empty.