httputil

package
v0.1.16 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package httputil provides three helpers for HTTP handlers: Bind() parses and validates request bodies, Handle() wraps handler functions that return errors into standard http.Handler, and OK()/Created()/JSON() write JSON responses.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindForm

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

BindForm decodes form data into T and validates it.

func BindJSON

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

BindJSON decodes a JSON request body into T and validates it. Replaces manual json.NewDecoder + validate blocks with one line.

func BindQuery

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

BindQuery decodes URL query parameters into T and validates it.

func Created

func Created(w http.ResponseWriter, data interface{}) error

Created writes a 201 Created JSON response.

func DecodeForm added in v0.1.7

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

DecodeForm decodes form data into T and returns it. Validation is the caller's responsibility — see the DecodeJSON doc for the recommended caller pattern.

func DecodeJSON added in v0.1.7

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

DecodeJSON decodes a JSON request body into T and returns it.

Unlike BindJSON, DecodeJSON does not validate the result — validation belongs at the controller boundary using the project's configured validator (typically validators.AppValidator), which has access to the project's custom validation functions (uuid4_valid, is_record_exist_by_*, etc.). BindJSON's hardcoded internal validator panics on those tags, so callers that depend on custom validation should use DecodeJSON + their own ValidateStruct call:

in, err := httputil.DecodeJSON[dtos.TUpdateUserDto](r)
if err != nil { return err }
if errs := c.validator.ValidateStruct(in); len(errs) > 0 {
    return apperrors.NewValidation("invalid input", errs)
}

Returns an apperrors.BadRequest on malformed JSON so the framework error middleware can map it to a 400 response.

func DecodeQuery added in v0.1.7

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

DecodeQuery decodes URL query parameters into T and returns it. Like DecodeJSON, validation is the caller's responsibility — see the DecodeJSON doc for the recommended caller pattern.

func ETagOf added in v0.1.8

func ETagOf(version string) string

ETagOf formats a record version (or any opaque revision token) as a strong ETag value: `"<v>"`. Use the result as the value of an ETag response header so callers can supply it back as If-Match on a follow-up PUT/PATCH/DELETE.

w.Header().Set("ETag", httputil.ETagOf("3"))   // ETag: "3"

Strong validators (no W/ prefix) are correct here because the body is byte-identical for the same record version — there is no transformation that would justify weak comparison.

func Handle

func Handle(h AppHandler) http.HandlerFunc

Handle converts an AppHandler into a standard http.HandlerFunc. If the handler returns an *AppError, it writes a structured JSON error response; a 5xx AppError is also logged with its wrapped cause, which the body never exposes. Unknown errors are logged and a generic 500 is returned.

func JSON

func JSON(w http.ResponseWriter, status int, data interface{}) error

JSON writes a JSON response with the given status code and data.

func NoContent

func NoContent(w http.ResponseWriter) error

NoContent writes a 204 No Content response.

func OK

func OK(w http.ResponseWriter, data interface{}) error

OK writes a 200 OK JSON response.

func ParseIfMatch added in v0.1.8

func ParseIfMatch(r *http.Request) (string, error)

ParseIfMatch returns the unquoted If-Match value from r. The value is what the server originally emitted as the resource's ETag — the caller compares it against current server state.

Behavior:

  • missing header → ("", apperrors.PreconditionRequired)
  • present but only "*" (match-any) → ("*", nil) — RFC 7232 §3.1
  • present with one quoted token → unquoted value, nil
  • present with multiple comma-sep vals → first token unquoted, nil
  • W/"<v>" (weak validator) → "<v>", nil — accepted

The PreconditionRequired error carries an HTTP 428 mapping so an AppError-aware middleware (httputil.Handle) translates it without the controller needing to set a status code itself.

func SetETag added in v0.1.8

func SetETag(w http.ResponseWriter, version string)

SetETag is a convenience wrapper around w.Header().Set("ETag", ...) + ETagOf. Slightly shorter at the call site:

httputil.SetETag(w, "3")

Types

type AppHandler

type AppHandler func(w http.ResponseWriter, r *http.Request) error

AppHandler is an http.HandlerFunc that returns an error. Errors are handled centrally by the Handle adapter.

Jump to

Keyboard shortcuts

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