httputil

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

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"

Variables

This section is empty.

Functions

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,
	log *slog.Logger,
	operation string,
) (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 is *httperr.HTTPError, uses its status and code; otherwise 500.

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 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, maxMemory int64) bool

ParseMultipartFormLimit parses multipart form with maxMemory limit. On error writes response and returns false.

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 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 ValidateSearchQ

func ValidateSearchQ(q string) bool

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

Types

type ErrorResponse

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

ErrorResponse is the JSON shape for error responses.

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

Jump to

Keyboard shortcuts

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