httputil

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 21 Imported by: 0

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

View Source
const DefaultSearchMaxLen = 100
View Source
const MaxPage = 10000
View Source
const MaxRequestBodySize = 1 << 20
View Source
const UserIDKey contextKey = "user_id"

UserIDKey is the context key for the authenticated user ID (string, e.g. UUID). Set by auth middleware.

Variables

View Source
var ErrSSEClosed = errors.New("SSE writer closed")

Functions

func ChiPathFromRequest added in v0.1.1

func ChiPathFromRequest(r *http.Request) string

ChiPathFromRequest returns the route pattern from chi's RouteContext, or empty string if none.

func ClampLimit

func ClampLimit(p *int, defaultVal, maxVal int) int

ClampLimit returns limit clamped to [defaultVal, maxVal], or defaultVal if nil/<=0.

func ClampPage

func ClampPage(p *int) int

ClampPage returns page clamped to [1, MaxPage].

func ClampPerPage

func ClampPerPage(p *int, defaultVal, maxVal int) int

ClampPerPage returns perPage clamped to [defaultVal, maxVal], or defaultVal if nil/<=0.

func DecodeAndValidate

func DecodeAndValidate[T any](w http.ResponseWriter, r *http.Request, v Validator) (T, bool)

DecodeAndValidate reads and validates JSON from the request body. On error writes response and returns false.

func DecodeAndValidateE

func DecodeAndValidateE[T any](r *http.Request, v Validator) (T, error)

DecodeAndValidateE reads and validates JSON from the request body and returns an error without writing response.

func DecodeJSON

func DecodeJSON[T any](r *http.Request, v *T) error

DecodeJSON decodes JSON from the request body with size limit and no trailing data.

func EscapeILIKE

func EscapeILIKE(s string, maxLen int) string

EscapeILIKE escapes %, _, \ for safe use in PostgreSQL ILIKE.

func GetClientIP

func GetClientIP(r *http.Request, trustedProxyCIDRs []string) string

GetClientIP returns the client IP, considering X-Real-IP and X-Forwarded-For when remote is in trustedProxyCIDRs.

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID returns the user ID from context (set by auth middleware).

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

func ParseAuthUserID(w http.ResponseWriter, r *http.Request) (uuid.UUID, bool)

ParseAuthUserID returns the authenticated user's UUID from context or writes error.

func ParseBoolQuery added in v0.1.3

func ParseBoolQuery(r *http.Request, key string) (bool, bool)

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

func ParseEnumQuery[T ~string](r *http.Request, key string, allowed []T) (T, bool)

ParseEnumQuery parses the query parameter key and returns it as T if it is in the allowed slice; otherwise ("", false).

func ParseIntQuery

func ParseIntQuery(r *http.Request, key string) *int

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

func ParseSortQuery(r *http.Request, allowedFields []string) (field, dir string, ok bool)

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

func ParseTimeQuery(r *http.Request, key, layout string) (time.Time, bool)

ParseTimeQuery parses the query parameter key with the given time layout (e.g. time.RFC3339). Returns (zero, false) on missing or invalid value.

func ParseUUID

func ParseUUID(w http.ResponseWriter, r *http.Request, id string) (uuid.UUID, bool)

ParseUUID parses id from path/query and writes error response on failure.

func ParseUUIDField

func ParseUUIDField(w http.ResponseWriter, r *http.Request, value, field string) (uuid.UUID, bool)

ParseUUIDField parses value as UUID for a given field name (validation error).

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v.

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

func RenderError(w http.ResponseWriter, r *http.Request, status int, message string)

RenderError sends JSON error with status and message; code is derived from status.

func RenderErrorWithCode

func RenderErrorWithCode(w http.ResponseWriter, r *http.Request, status int, message, code string)

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

func RenderJSON[T any](w http.ResponseWriter, r *http.Request, status int, data T)

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

func RenderStream(w http.ResponseWriter, contentType, filename string, rc io.Reader) error

RenderStream writes a streaming response with Content-Disposition attachment. Caller must close rc.

func RenderText

func RenderText(w http.ResponseWriter, _ *http.Request, status int, contentType, body string)

RenderText writes a text response with given content type and body.

func SanitizeSearchQ

func SanitizeSearchQ(q string, maxLen int) string

SanitizeSearchQ is EscapeILIKE with default max length.

func TotalPages added in v0.1.2

func TotalPages(total int64, perPage int) int

func ValidateSearchQ

func ValidateSearchQ(q string) bool

ValidateSearchQ returns true if q is valid for search (length and no control chars).

Types

type Checker added in v0.1.3

type Checker interface {
	Check(ctx context.Context) error
}

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 ErrorLogEvent interface {
	Info(msg string)
	Error(msg string)
}

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

type ErrorResponse struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

ErrorResponse is the JSON shape for error responses.

type PaginationMeta added in v0.1.2

type PaginationMeta struct {
	Page       int
	PerPage    int
	Total      int
	TotalPages int
}

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.

func (*SSEWriter) Send added in v0.1.3

func (s *SSEWriter) Send(event, data string) error

Send writes an SSE message: optional "event: <event>\n" and "data: <line>\n" per line of data, then "\n". Flushes after write.

func (*SSEWriter) SendJSON added in v0.1.3

func (s *SSEWriter) SendJSON(event string, v any) error

SendJSON marshals v to JSON and sends it as the data payload via Send.

type ValidationErrorItem

type ValidationErrorItem struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

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.

type Validator

type Validator interface {
	Validate(any) error
}

Validator validates structs (e.g. go-playground/validator).

Directories

Path Synopsis
Package middleware provides HTTP middleware for go-httpkit.
Package middleware provides HTTP middleware for go-httpkit.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL