Documentation
¶
Overview ¶
Package httputil provides HTTP helpers: error handling and JSON responses, request decoding and validation, pagination (ClampPage, ClampPerPage, ParseIntQuery), query parsing (ParseBoolQuery, ParseEnumQuery, ParseSortQuery, ParseTimeQuery), client IP resolution with proxy headers, search sanitization (EscapeILIKE), multipart limits, file download responses, chi route pattern (ChiPathFromRequest), SSE (SSEWriter, NewSSEWriter), and health checks (Checker, HealthHandler).
Index ¶
- Constants
- Variables
- func ChiPathFromRequest(r *http.Request) string
- func ClampLimit(p *int, defaultVal, maxVal int) int
- func ClampPage(p *int) int
- func ClampPerPage(p *int, defaultVal, maxVal int) int
- func DecodeAndValidate[T any](w http.ResponseWriter, r *http.Request, v Validator) (T, bool)
- func DecodeAndValidateE[T any](r *http.Request, v Validator) (T, error)
- func DecodeJSON[T any](r *http.Request, v *T) error
- func EscapeILIKE(s string, maxLen int) string
- func GetClientIP(r *http.Request, trustedProxyCIDRs []string) string
- func GetUserID(ctx context.Context) string
- func HandleError(w http.ResponseWriter, r *http.Request, err error)
- func HealthHandler(checkers map[string]Checker) http.HandlerFunc
- func ParseAuthUserID(w http.ResponseWriter, r *http.Request) (uuid.UUID, bool)
- func ParseBoolQuery(r *http.Request, key string) (bool, bool)
- func ParseEnumQuery[T ~string](r *http.Request, key string, allowed []T) (T, bool)
- func ParseIntQuery(r *http.Request, key string) *int
- func ParseMultipartFormLimit(w http.ResponseWriter, r *http.Request, maxBodySize, maxMemory int64) bool
- func ParseSortQuery(r *http.Request, allowedFields []string) (field, dir string, ok bool)
- func ParseTimeQuery(r *http.Request, key, layout string) (time.Time, bool)
- func ParseUUID(w http.ResponseWriter, r *http.Request, id string) (uuid.UUID, bool)
- func ParseUUIDField(w http.ResponseWriter, r *http.Request, value, field string) (uuid.UUID, bool)
- func Ptr[T any](v T) *T
- func RenderAccepted[T any](w http.ResponseWriter, r *http.Request, data T)
- func RenderBytes(w http.ResponseWriter, contentType, filename string, data []byte) error
- func RenderCreated[T any](w http.ResponseWriter, r *http.Request, data T)
- func RenderError(w http.ResponseWriter, r *http.Request, status int, message string)
- func RenderErrorWithCode(w http.ResponseWriter, r *http.Request, status int, message, code string)
- func RenderInvalidID(w http.ResponseWriter, r *http.Request)
- func RenderJSON[T any](w http.ResponseWriter, r *http.Request, status int, data T)
- func RenderJSONAttachment[T any](w http.ResponseWriter, data T, filename string) error
- func RenderNoContent(w http.ResponseWriter, _ *http.Request)
- func RenderOK[T any](w http.ResponseWriter, r *http.Request, data T)
- func RenderStream(w http.ResponseWriter, contentType, filename string, rc io.Reader) error
- func RenderText(w http.ResponseWriter, _ *http.Request, status int, contentType, body string)
- func SanitizeSearchQ(q string, maxLen int) string
- func TotalPages(total int64, perPage int) int
- func ValidateSearchQ(q string) bool
- type Checker
- type ErrorHandler
- type ErrorLogEvent
- type ErrorLogger
- type ErrorResponse
- type PaginationMeta
- type SSEWriter
- type ValidationErrorItem
- type ValidationErrorResponse
- type Validator
Constants ¶
const DefaultSearchMaxLen = 100
const MaxPage = 10000
const MaxRequestBodySize = 1 << 20
const UserIDKey contextKey = "user_id"
UserIDKey is the context key for the authenticated user ID (string, e.g. UUID). Set by auth middleware.
Variables ¶
var ErrSSEClosed = errors.New("SSE writer closed")
Functions ¶
func ChiPathFromRequest ¶ added in v0.1.1
ChiPathFromRequest returns the route pattern from chi's RouteContext, or empty string if none.
func ClampLimit ¶
ClampLimit returns limit clamped to [defaultVal, maxVal], or defaultVal if nil/<=0.
func ClampPerPage ¶
ClampPerPage returns perPage clamped to [defaultVal, maxVal], or defaultVal if nil/<=0.
func DecodeAndValidate ¶
DecodeAndValidate reads and validates JSON from the request body. On error writes response and returns false.
func DecodeAndValidateE ¶
DecodeAndValidateE reads and validates JSON from the request body and returns an error without writing response.
func DecodeJSON ¶
DecodeJSON decodes JSON from the request body with size limit and no trailing data.
func EscapeILIKE ¶
EscapeILIKE escapes %, _, \ for safe use in PostgreSQL ILIKE.
func GetClientIP ¶
GetClientIP returns the client IP, considering X-Real-IP and X-Forwarded-For when remote is in trustedProxyCIDRs.
func HandleError ¶
func HandleError(w http.ResponseWriter, r *http.Request, err error)
HandleError writes a JSON error response. If err implements httpErrorWithStatus, uses its status and code; otherwise 500.
func HealthHandler ¶ added in v0.1.3
func HealthHandler(checkers map[string]Checker) http.HandlerFunc
HealthHandler returns a handler that runs all checkers and responds with JSON: {"status":"ok"|"degraded","checks":{name:"ok"|"error"}}. Status 200 when all pass, 503 when any check fails. Nil checkers are treated as ok.
func ParseAuthUserID ¶
ParseAuthUserID returns the authenticated user's UUID from context or writes error.
func ParseBoolQuery ¶ added in v0.1.3
ParseBoolQuery parses the query parameter key as a boolean. Accepts "1", "true", "yes" (true) and "0", "false", "no" (false). Returns (value, true) when valid, (false, false) when missing or invalid.
func ParseEnumQuery ¶ added in v0.1.3
ParseEnumQuery parses the query parameter key and returns it as T if it is in the allowed slice; otherwise ("", false).
func ParseIntQuery ¶
ParseIntQuery parses the first query parameter key as positive int; returns nil if missing or invalid.
func ParseMultipartFormLimit ¶
func ParseMultipartFormLimit(w http.ResponseWriter, r *http.Request, maxBodySize, maxMemory int64) bool
ParseMultipartFormLimit parses multipart form with maxBodySize (MaxBytesReader) and maxMemory (ParseMultipartForm). On error writes response and returns false.
func ParseSortQuery ¶ added in v0.1.3
ParseSortQuery parses the "sort" query parameter. Supports "field", "-field", or "field:asc"/"field:desc". Returns (field, dir, true) when the field is in allowedFields and dir is "asc" or "desc"; otherwise ("", "", false).
func ParseTimeQuery ¶ added in v0.1.3
ParseTimeQuery parses the query parameter key with the given time layout (e.g. time.RFC3339). Returns (zero, false) on missing or invalid value.
func ParseUUIDField ¶
ParseUUIDField parses value as UUID for a given field name (validation error).
func RenderAccepted ¶ added in v0.1.1
func RenderAccepted[T any](w http.ResponseWriter, r *http.Request, data T)
RenderAccepted sends 202 Accepted with JSON body.
func RenderBytes ¶
func RenderBytes(w http.ResponseWriter, contentType, filename string, data []byte) error
RenderBytes writes raw bytes with Content-Disposition attachment.
func RenderCreated ¶
func RenderCreated[T any](w http.ResponseWriter, r *http.Request, data T)
RenderCreated sends 201 Created with JSON body.
func RenderError ¶
RenderError sends JSON error with status and message; code is derived from status.
func RenderErrorWithCode ¶
RenderErrorWithCode sends JSON error with explicit code.
func RenderInvalidID ¶
func RenderInvalidID(w http.ResponseWriter, r *http.Request)
RenderInvalidID sends 400 with INVALID_ID code.
func RenderJSON ¶
RenderJSON writes data as JSON with the given status.
func RenderJSONAttachment ¶
func RenderJSONAttachment[T any](w http.ResponseWriter, data T, filename string) error
RenderJSONAttachment encodes data as JSON and writes it as a downloadable attachment.
func RenderNoContent ¶
func RenderNoContent(w http.ResponseWriter, _ *http.Request)
RenderNoContent sends 204 No Content.
func RenderOK ¶
func RenderOK[T any](w http.ResponseWriter, r *http.Request, data T)
RenderOK sends 200 OK with JSON body.
func RenderStream ¶
RenderStream writes a streaming response with Content-Disposition attachment. Caller must close rc.
func RenderText ¶
RenderText writes a text response with given content type and body.
func SanitizeSearchQ ¶
SanitizeSearchQ is EscapeILIKE with default max length.
func TotalPages ¶ added in v0.1.2
func ValidateSearchQ ¶
ValidateSearchQ returns true if q is valid for search (length and no control chars).
Types ¶
type Checker ¶ added in v0.1.3
Checker performs a single health check. Check returns nil for success.
type ErrorHandler ¶ added in v0.1.2
type ErrorHandler struct {
Logger ErrorLogger
}
func (*ErrorHandler) Handle ¶ added in v0.1.2
func (h *ErrorHandler) Handle(w http.ResponseWriter, r *http.Request, err error, msg string) bool
type ErrorLogEvent ¶ added in v0.1.2
type ErrorLogger ¶ added in v0.1.2
type ErrorLogger interface {
WithError(err error) ErrorLogEvent
}
func NewErrorLogger ¶ added in v0.1.2
func NewErrorLogger(l logger.Logger) ErrorLogger
type ErrorResponse ¶
ErrorResponse is the JSON shape for error responses.
type PaginationMeta ¶ added in v0.1.2
func NewPaginationMeta ¶ added in v0.1.2
func NewPaginationMeta(page, perPage int, total int64) PaginationMeta
type SSEWriter ¶ added in v0.1.3
type SSEWriter struct {
// contains filtered or unexported fields
}
SSEWriter sends Server-Sent Events. Use NewSSEWriter to create; it returns (nil, false) if w does not implement http.Flusher.
func NewSSEWriter ¶ added in v0.1.3
func NewSSEWriter(w http.ResponseWriter) (*SSEWriter, bool)
NewSSEWriter configures w for SSE (Content-Type, Cache-Control, etc.) and returns a writer. Second return is false if w is not flushable.
func (*SSEWriter) Close ¶ added in v0.1.3
func (s *SSEWriter) Close()
Close marks the writer as done; subsequent Send/SendJSON calls are no-ops.
type ValidationErrorItem ¶
ValidationErrorItem represents a single validation error.
type ValidationErrorResponse ¶
type ValidationErrorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
Errors []ValidationErrorItem `json:"errors,omitempty"`
}
ValidationErrorResponse is the JSON shape for validation errors.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package middleware provides HTTP middleware for go-httpkit.
|
Package middleware provides HTTP middleware for go-httpkit. |