« Back to Search  |  Reader Mode  |  Switch to Full Retro Site View Links: Stay in Reader  |  Retro Mode: ON  |  Original »
pkg.go.dev · Extracted in 485 ms

httpsuite package - github.com/rluders/httpsuite/v3 - Go Packages

Source: https://pkg.go.dev/github.com/rluders/httpsuite/v3

httpsuite

package module v3.1.0 Latest Latest

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

Go to latest Published: Oct 23, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

httpsuite

httpsuite is a Go library for request parsing, response writing, and RFC 9457 problem responses.

v3 keeps the root module stdlib-only and moves validation to an optional submodule.

Features

  • Parse JSON request bodies with a default 1 MiB limit
  • Return 413 Payload Too Large when the configured body limit is exceeded
  • Bind path params explicitly through a router-specific extractor
  • Validate automatically during ParseRequest when a global validator is configured
  • Keep ParseRequest panic-safe for invalid inputs and return regular errors instead
  • Return consistent RFC 9457 Problem Details
  • Write success responses with optional generic metadata
  • Support both direct helpers and optional builders

Why httpsuite?

Writing HTTP handlers in Go often leads to repetitive and error-prone code:

  • Manual JSON decoding
  • Manual validation wiring
  • Ad-hoc path parameter extraction
  • Inconsistent error handling
  • Repeated boilerplate across handlers

httpsuite provides a consistent and safe flow for parsing requests and writing responses, while staying lightweight and idiomatic.

What you gain

Less boilerplate

A single entry point replaces multiple manual steps:

req, err := httpsuite.ParseRequest[*MyRequest](w, r, chi.URLParam, nil, "id")
if err != nil {
    return
}
  • JSON decoding
  • Path param binding
  • Optional validation

All handled in one place, reducing handler complexity.

Safe by default
  • ParseRequest never panics on invalid inputs
  • Handles nil request and nil body safely
  • Enforces body size limits with proper HTTP responses

This reduces the risk of runtime crashes and undefined behavior.

Consistent error responses

Errors follow RFC 9457 Problem Details out of the box.

Instead of ad-hoc responses like:

{ "error": "invalid request" }

You get structured, standardized responses:

{
  "type": "...",
  "title": "...",
  "status": 400,
  "detail": "..."
}

This improves API consistency and client integration.

Centralized validation
  • Configure once with SetValidator(...)
  • Automatically applied during ParseRequest
  • Can be overridden per request

This eliminates duplicated validation logic across handlers.

Lightweight and modular
  • Core module is stdlib-only
  • No framework lock-in
  • Validation is optional

You keep full control over your stack.

Flexible response API

Choose the level of abstraction you need:

Simple

httpsuite.OK(w, data)

Fluent

httpsuite.Reply().Meta(meta).OK(w, data)

Advanced

httpsuite.Problem(...).Title(...).Build()
Router-agnostic

Works with:

  • Chi
  • Gorilla Mux
  • net/http

No need to change your router or architecture.

Comparison

❌ Without httpsuite
var req MyRequest

if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
    http.Error(w, "invalid body", 400)
    return
}

idStr := chi.URLParam(r, "id")
id, err := strconv.Atoi(idStr)
if err != nil {
    http.Error(w, "invalid id", 400)
    return
}

// validation...
// more error handling...

Problems:

  • Repeated logic across handlers
  • Inconsistent error formats
  • Easy to miss edge cases
✅ With httpsuite
req, err := httpsuite.ParseRequest[*MyRequest](w, r, chi.URLParam, nil, "id")
if err != nil {
    return
}

httpsuite.OK(w, req)

Benefits:

  • Single, consistent flow
  • Less code
  • Safer defaults

Supported routers

  • Chi
  • Gorilla Mux
  • Go standard http.ServeMux

Installation

Core
go get github.com/rluders/httpsuite/v3
Optional validation adapter
go get github.com/rluders/httpsuite/validation/playground

Mental model

  • request in: ParseRequest(...)
  • success out: OK(...), Created(...), Reply().Meta(...).OK(...)
  • problem out: ProblemResponse(...), NewBadRequestProblem(...), Problem(...).Build()
  • validation: configure once with SetValidator(...), override locally with ParseOptions.Validator

For simple handlers, prefer direct helpers.

When a handler needs custom headers, metadata, or problem composition, use the optional builders.

ParseRequest never panics on invalid inputs such as a nil request, nil body, or nil path extractor. These cases return regular Go errors so callers can fail safely.

Quick start

Core only
package main

import (
	"net/http"
	"strconv"

	"github.com/go-chi/chi/v5"
	"github.com/rluders/httpsuite/v3"
)

type CreateUserRequest struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func (r *CreateUserRequest) SetParam(fieldName, value string) error {
	if fieldName != "id" {
		return nil
	}

	id, err := strconv.Atoi(value)
	if err != nil {
		return err
	}
	r.ID = id
	return nil
}

func main() {
	router := chi.NewRouter()

	router.Post("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
		req, err := httpsuite.ParseRequest[*CreateUserRequest](w, r, chi.URLParam, nil, "id")
		if err != nil {
			return
		}

		httpsuite.OK(w, req)
	})

	_ = http.ListenAndServe(":8080", router)
}

Try it:

curl -X POST http://localhost:8080/users/123 \
  -H "Content-Type: application/json" \
  -d '{"name":"Ada"}'
Core + validation
validator := playground.NewWithValidator(nil, &httpsuite.ProblemConfig{
	BaseURL: "https://api.example.com",
})

httpsuite.SetValidator(validator)

req, err := httpsuite.ParseRequest[*CreateUserRequest](
	w,
	r,
	chi.URLParam,
	&httpsuite.ParseOptions{
		MaxBodyBytes: 1 << 20,
	},
	"id",
)
Problem type URLs

Set the base URL and extra error type paths once at startup; GetProblemTypeURL and the problem helpers pick them up. ParseOptions.Problems still overrides per call.

cfg := httpsuite.NewProblemConfig()
cfg.BaseURL = "https://api.example.com"
cfg.ErrorTypePaths["payment_required_error"] = "/errors/payment-required"
httpsuite.SetProblemConfig(cfg)

// restore the built-in default
httpsuite.SetProblemConfig(httpsuite.NewProblemConfig())

Direct helpers

httpsuite.OK(w, user)
httpsuite.OKWithMeta(w, users, httpsuite.NewPageMeta(page, pageSize, totalItems))
httpsuite.Created(w, user, "/users/42")
httpsuite.Accepted(w, job)
httpsuite.NoContent(w)
httpsuite.ProblemResponse(w, httpsuite.NewNotFoundProblem("user not found"))
httpsuite.ProblemResponse(w, httpsuite.NewUnauthorizedProblem("missing token"))
httpsuite.ProblemResponse(w, httpsuite.NewForbiddenProblem("admin only"))
httpsuite.ProblemResponse(w, httpsuite.NewConflictProblem("email already taken"))
httpsuite.ProblemResponse(w, httpsuite.NewUnprocessableProblem("order already shipped"))
httpsuite.ProblemResponse(w, httpsuite.NewInternalProblem("unexpected error"))

Fluent helpers

httpsuite.Reply().
	Meta(httpsuite.NewPageMeta(page, pageSize, totalItems)).
	OK(w, users)

httpsuite.Reply().
	Header("X-Request-ID", requestID).
	Created(w, user, "/users/42")

httpsuite.Reply().
	Header("Location", "/jobs/7").
	Accepted(w, job)

httpsuite.Reply().
	Header("X-Request-ID", requestID).
	NoContent(w)

Builders

problem := httpsuite.Problem(http.StatusNotFound).
	Type(httpsuite.GetProblemTypeURL("not_found_error")).
	Title("User Not Found").
	Detail("user 42 does not exist").
	Instance("/users/42").
	Build()

httpsuite.RespondProblem(problem).
	Header("X-Trace-ID", traceID).
	Write(w)

Precognition

Let clients validate a request against the endpoint's real decoding, binding and validation rules without running business logic. Opt in per endpoint:

req, err := httpsuite.ParseRequest[*CreateUserRequest](w, r, chi.URLParam, &httpsuite.ParseOptions{
	Precognition: true,
}, "id")
if err != nil {
	// Covers parse errors, validation errors and handled precognitive requests.
	return
}

// Never reached for a precognitive request.
user := store.Create(req)

A client sends the same request with Precognition: true:

Outcome Response err
Valid 204 No Content, Precognition-Success: true ErrPrecognitionHandled
Validation failed 422 with the validator's ProblemDetails validation error
Malformed body / too large / bad path param usual 400 / 413 problem parse error

Notes:

  • Without ParseOptions.Precognition, the header is ignored and the request is processed normally.
  • Opted-in endpoints add Vary: Precognition to responses.
  • Use httpsuite.IsPrecognitionHandled(err) to tell a handled precognitive request apart from a failure, and httpsuite.IsPrecognitionRequest(r) to inspect the request.
  • With SkipValidation, a precognitive request only checks decoding and path binding.
  • A successful pre-validation does not guarantee the real request will succeed; state may change in between.

Architecture

  • root module: github.com/rluders/httpsuite/v3
  • optional validation adapter: github.com/rluders/httpsuite/validation/playground
  • root stays stdlib-only
  • validation is opt-in at bootstrap, automatic at parse time when configured
  • response metadata is generic and can use PageMeta or CursorMeta

Migration from v2 to v3

  • update imports from v2 to v3
  • update ParseRequest calls to pass opts before pathParams
  • configure validation globally with httpsuite.SetValidator(...)
  • ParseRequest now validates automatically when a validator is configured
  • validator-provided status is respected
  • use ParseOptions.SkipValidation to opt out per call
  • use ParseOptions.Validator to override per call
  • use ProblemConfig for custom problem type URLs

Examples

Examples live in examples/.

  • examples/stdmux: core-only with http.ServeMux
  • examples/gorillamux: path params with Gorilla Mux
  • examples/chi: global validation with Chi
  • examples/restapi: full REST example with pagination and custom problems

Notes for contributors

  • request helpers: request*.go
  • response helpers/builders: response*.go
  • problem handling: problem*.go

Release workflow

Supports:

  • pushing an existing v* tag
  • manual release with semantic version bump

Tutorial

Contributing

  • open an issue
  • submit a PR
  • add a router example

License

MIT

Documentation

Index

Constants

View Source
const BlankURL = "about:blank"
View Source
const PrecognitionHeader = "Precognition"

PrecognitionHeader is the request header a client sends to ask for validation-only processing on an endpoint that enables ParseOptions.Precognition.

View Source
const PrecognitionSuccessHeader = "Precognition-Success"

PrecognitionSuccessHeader is set on the 204 response of a successful precognitive request.

Variables

View Source
var ErrPrecognitionHandled = errors.New("precognition request handled")

ErrPrecognitionHandled is returned by ParseRequest when a precognitive request was validated and the response has already been written. Handlers must stop processing; the usual `if err != nil { return }` does exactly that.

Functions

func Accepted
added in
v3.1.0

func Accepted[T any](w http.ResponseWriter, data T)

Accepted writes a 202 JSON response without metadata.

func BindPathParams

func BindPathParams[T any](request T, r *http.Request, paramExtractor ParamExtractor, pathParams ...string) (T, error)

BindPathParams applies extracted path params to a request object without writing HTTP responses.

func ClearValidator

func ClearValidator()

ClearValidator removes the package-level default validator.

func Created

func Created[T any](w http.ResponseWriter, data T, location string)

Created writes a 201 JSON response and optionally sets the Location header.

func DecodeRequestBody

func DecodeRequestBody[T any](r *http.Request, maxBodyBytes int64) (T, error)

DecodeRequestBody decodes a JSON request body into T without writing HTTP responses.

func GetProblemTypeURL

func GetProblemTypeURL(errorType string) string

GetProblemTypeURL returns the default problem type URL for a known error type.

func IsPrecognitionHandled
added in
v3.1.0

func IsPrecognitionHandled(err error) bool

IsPrecognitionHandled reports whether err signals a handled precognitive request.

func IsPrecognitionRequest
added in
v3.1.0

func IsPrecognitionRequest(r *http.Request) bool

IsPrecognitionRequest reports whether the request asks for validation-only processing.

func NoContent
added in
v3.1.0

func NoContent(w http.ResponseWriter)

NoContent writes a 204 response with no body.

func OK

func OK[T any](w http.ResponseWriter, data T)

OK writes a 200 JSON response without metadata.

func OKWithMeta

func OKWithMeta[T any](w http.ResponseWriter, data T, meta any)

OKWithMeta writes a 200 JSON response with metadata.

func ParseRequest

func ParseRequest[T any](w http.ResponseWriter, r *http.Request, paramExtractor ParamExtractor, opts *ParseOptions, pathParams ...string) (T, error)

ParseRequest parses the incoming HTTP request into a specified struct type, handling JSON decoding, request body limits, path parameter binding, and optional validation. Invalid inputs return regular errors instead of panicking. With ParseOptions.Precognition enabled, a request carrying the Precognition header stops after validation and ParseRequest returns ErrPrecognitionHandled.

func ProblemResponse

func ProblemResponse(w http.ResponseWriter, problem *ProblemDetails)

ProblemResponse writes a problem response using the problem's status.

func SendResponse

func SendResponse[T any](w http.ResponseWriter, code int, data T, problem *ProblemDetails, meta any)

SendResponse sends a JSON response to the client, supporting both success and error scenarios.

func SetProblemConfig
added in
v3.1.0

func SetProblemConfig(cfg ProblemConfig)

SetProblemConfig replaces the package-level default config used by GetProblemTypeURL, DefaultProblemConfig and the helpers that resolve problem types. The config is copied, so later changes to cfg do not affect the default. A per-call ParseOptions.Problems still overrides it.

Call it once at startup. To restore the built-in default, call SetProblemConfig(NewProblemConfig()).

func SetValidator

func SetValidator(v Validator)

SetValidator configures the package-level default validator used by ParseRequest.

Types

type BodyDecodeError

type BodyDecodeError struct {
	Kind  BodyDecodeErrorKind
	Err   error
	Limit int64
}

BodyDecodeError represents a request body parsing error.

func (*BodyDecodeError) Error

func (e *BodyDecodeError) Error() string

func (*BodyDecodeError) Unwrap

func (e *BodyDecodeError) Unwrap() error

type BodyDecodeErrorKind

type BodyDecodeErrorKind string

BodyDecodeErrorKind identifies the decode failure category.

const (
	BodyDecodeErrorInvalidJSON       BodyDecodeErrorKind = "invalid_json"
	BodyDecodeErrorBodyTooLarge      BodyDecodeErrorKind = "body_too_large"
	BodyDecodeErrorMultipleDocuments BodyDecodeErrorKind = "multiple_documents"
)

type CursorMeta

type CursorMeta struct {
	NextCursor string `json:"next_cursor,omitempty"`
	PrevCursor string `json:"prev_cursor,omitempty"`
	HasNext    bool   `json:"has_next"`
	HasPrev    bool   `json:"has_prev"`
}

CursorMeta provides cursor-based pagination details.

func NewCursorMeta

func NewCursorMeta(nextCursor, prevCursor string, hasNext, hasPrev bool) *CursorMeta

NewCursorMeta builds cursor-based metadata.

type Meta

type Meta = PageMeta

Meta is kept as a compatibility alias for page-based pagination metadata.

type PageMeta

type PageMeta struct {
	Page       int `json:"page,omitempty"`
	PageSize   int `json:"page_size,omitempty"`
	TotalPages int `json:"total_pages,omitempty"`
	TotalItems int `json:"total_items,omitempty"`
}

PageMeta provides page-based pagination details.

func NewPageMeta

func NewPageMeta(page, pageSize, totalItems int) *PageMeta

NewPageMeta builds page-based metadata and derives total pages when possible.

type ParamExtractor

type ParamExtractor func(r *http.Request, key string) string

ParamExtractor extracts a path parameter from a request.

type ParseOptions

type ParseOptions struct {
	MaxBodyBytes   int64
	Problems       *ProblemConfig
	Validator      Validator
	SkipValidation bool
	// Precognition enables validation-only processing for requests that send
	// the Precognition: true header. Such requests are decoded, bound and
	// validated as usual; on success ParseRequest writes 204 No Content and
	// returns ErrPrecognitionHandled, on validation failure it writes the
	// validator's problem with status 422. When false, the header is ignored.
	Precognition bool
}

ParseOptions configures request parsing behavior.

type PathParamError

type PathParamError struct {
	Param   string
	Missing bool
	Err     error
}

PathParamError represents a path parameter binding error.

func (*PathParamError) Error

func (e *PathParamError) Error() string

func (*PathParamError) Unwrap

func (e *PathParamError) Unwrap() error

type ProblemBuilder

type ProblemBuilder struct {
	// contains filtered or unexported fields
}

ProblemBuilder builds ProblemDetails declaratively.

func Problem

func Problem(status int) *ProblemBuilder

Problem starts a declarative ProblemDetails builder.

func ProblemBadRequest

func ProblemBadRequest(detail string) *ProblemBuilder

ProblemBadRequest returns a bad request problem builder.

func ProblemConflict
added in
v3.1.0

func ProblemConflict(detail string) *ProblemBuilder

ProblemConflict returns a conflict problem builder.

func ProblemForbidden
added in
v3.1.0

func ProblemForbidden(detail string) *ProblemBuilder

ProblemForbidden returns a forbidden problem builder.

func ProblemInternal
added in
v3.1.0

func ProblemInternal(detail string) *ProblemBuilder

ProblemInternal returns an internal server error problem builder.

func ProblemNotFound

func ProblemNotFound(detail string) *ProblemBuilder

ProblemNotFound returns a not found problem builder.

func ProblemUnauthorized
added in
v3.1.0

func ProblemUnauthorized(detail string) *ProblemBuilder

ProblemUnauthorized returns an unauthorized problem builder.

func ProblemUnprocessable
added in
v3.1.0

func ProblemUnprocessable(detail string) *ProblemBuilder

ProblemUnprocessable returns an unprocessable entity problem builder.

func (*ProblemBuilder) Build

func (b *ProblemBuilder) Build() *ProblemDetails

Build returns the configured ProblemDetails.

func (*ProblemBuilder) Detail

func (b *ProblemBuilder) Detail(detail string) *ProblemBuilder

Detail sets the problem detail.

func (*ProblemBuilder) Extension

func (b *ProblemBuilder) Extension(key string, value any) *ProblemBuilder

Extension sets a single problem extension.

func (*ProblemBuilder) Extensions

func (b *ProblemBuilder) Extensions(values map[string]any) *ProblemBuilder

Extensions merges multiple problem extensions.

func (*ProblemBuilder) Instance

func (b *ProblemBuilder) Instance(instance string) *ProblemBuilder

Instance sets the problem instance.

func (*ProblemBuilder) Title

func (b *ProblemBuilder) Title(title string) *ProblemBuilder

Title sets the problem title.

func (*ProblemBuilder) Type

func (b *ProblemBuilder) Type(problemType string) *ProblemBuilder

Type sets the problem type URL.

type ProblemConfig

type ProblemConfig struct {
	BaseURL        string
	ErrorTypePaths map[string]string
}

ProblemConfig controls how problem type URLs are generated.

func DefaultProblemConfig

func DefaultProblemConfig() ProblemConfig

DefaultProblemConfig returns a copy of the package default config.

func NewProblemConfig

func NewProblemConfig() ProblemConfig

NewProblemConfig returns a config preloaded with the default problem type paths.

func (ProblemConfig) Clone

func (c ProblemConfig) Clone() ProblemConfig

Clone returns a deep copy of the config.

func (ProblemConfig) TypeURL

func (c ProblemConfig) TypeURL(errorType string) string

TypeURL builds the full type URL for a known error type.

type ProblemDetails

type ProblemDetails struct {
	Type     string `json:"type"`
	Title    string `json:"title"`
	Status   int    `json:"status"`
	Detail   string `json:"detail,omitempty"`
	Instance string `json:"instance,omitempty"`
	// Extensions holds RFC 9457 extension members. MarshalJSON and
	// UnmarshalJSON flatten them to the top level; there is no nested
	// "extensions" object on the wire.
	Extensions map[string]interface{} `json:"-"`
}

ProblemDetails conforms to RFC 9457 , providing a standard format for describing errors in HTTP APIs.

func NewBadRequestProblem

func NewBadRequestProblem(detail string) *ProblemDetails

NewBadRequestProblem returns a ready-to-use bad request problem.

func NewConflictProblem
added in
v3.1.0

func NewConflictProblem(detail string) *ProblemDetails

NewConflictProblem returns a ready-to-use conflict problem.

func NewForbiddenProblem
added in
v3.1.0

func NewForbiddenProblem(detail string) *ProblemDetails

NewForbiddenProblem returns a ready-to-use forbidden problem.

func NewInternalProblem
added in
v3.1.0

func NewInternalProblem(detail string) *ProblemDetails

NewInternalProblem returns a ready-to-use internal server error problem.

func NewNotFoundProblem

func NewNotFoundProblem(detail string) *ProblemDetails

NewNotFoundProblem returns a ready-to-use not found problem.

func NewProblemDetails

func NewProblemDetails(status int, problemType, title, detail string) *ProblemDetails

NewProblemDetails creates a ProblemDetails instance with standard fields.

func NewUnauthorizedProblem
added in
v3.1.0

func NewUnauthorizedProblem(detail string) *ProblemDetails

NewUnauthorizedProblem returns a ready-to-use unauthorized problem.

func NewUnprocessableProblem
added in
v3.1.0

func NewUnprocessableProblem(detail string) *ProblemDetails

NewUnprocessableProblem returns a ready-to-use unprocessable entity problem.

func ValidateRequest

func ValidateRequest(request any, validator Validator) *ProblemDetails

ValidateRequest applies a validator without writing HTTP responses.

func (ProblemDetails) MarshalJSON

func (p ProblemDetails) MarshalJSON() ([]byte, error)

MarshalJSON serializes RFC 9457 extension members at the top level.

func (*ProblemDetails) UnmarshalJSON
added in
v3.1.0

func (p *ProblemDetails) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the standard RFC 9457 members and collects every other top-level member into Extensions, mirroring MarshalJSON. A JSON null leaves p unchanged, matching encoding/json semantics.

type ReplyBuilder

type ReplyBuilder struct {
	// contains filtered or unexported fields
}

ReplyBuilder configures metadata and headers before writing a response.

func Reply

func Reply() *ReplyBuilder

Reply starts a fluent response helper configuration.

func (*ReplyBuilder) Accepted
added in
v3.1.0

func (b *ReplyBuilder) Accepted(w http.ResponseWriter, data any)

Accepted writes a 202 JSON response using the fluent helper configuration.

func (*ReplyBuilder) Created

func (b *ReplyBuilder) Created(w http.ResponseWriter, data any, location string)

Created writes a 201 JSON response using the fluent helper configuration.

func (*ReplyBuilder) Header

func (b *ReplyBuilder) Header(key, value string) *ReplyBuilder

Header sets a single response header for a fluent helper chain.

func (*ReplyBuilder) Headers

func (b *ReplyBuilder) Headers(headers http.Header) *ReplyBuilder

Headers merges multiple response headers for a fluent helper chain.

func (*ReplyBuilder) Meta

func (b *ReplyBuilder) Meta(meta any) *ReplyBuilder

Meta sets response metadata for a fluent helper chain.

func (*ReplyBuilder) NoContent
added in
v3.1.0

func (b *ReplyBuilder) NoContent(w http.ResponseWriter)

NoContent writes a 204 response with no body using the fluent helper configuration. Metadata is ignored because a 204 response must not carry a body.

func (*ReplyBuilder) OK

func (b *ReplyBuilder) OK(w http.ResponseWriter, data any)

OK writes a 200 JSON response using the fluent helper configuration.

func (*ReplyBuilder) Problem

func (b *ReplyBuilder) Problem(w http.ResponseWriter, problem *ProblemDetails)

Problem writes a problem response using the fluent helper configuration.

type RequestParamSetter

type RequestParamSetter interface {
	SetParam(fieldName, value string) error
}

RequestParamSetter defines custom path parameter binding for request structs.

type Response

type Response[T any] struct {
	Data T   `json:"data"`
	Meta any `json:"meta,omitempty"`
}

Response represents the structure of an HTTP response, including an optional body and metadata.

type ResponseBuilder

type ResponseBuilder[T any] struct {
	// contains filtered or unexported fields
}

ResponseBuilder builds and writes HTTP responses declaratively.

func Respond

func Respond[T any](data T) *ResponseBuilder[T]

Respond starts a success response builder.

func RespondProblem

func RespondProblem(problem *ProblemDetails) *ResponseBuilder[any]

RespondProblem starts a problem response builder.

func (*ResponseBuilder[T]) Header

func (b *ResponseBuilder[T]) Header(key, value string) *ResponseBuilder[T]

Header sets a single response header.

func (*ResponseBuilder[T]) Headers

func (b *ResponseBuilder[T]) Headers(headers http.Header) *ResponseBuilder[T]

Headers merges multiple response headers.

func (*ResponseBuilder[T]) Meta

func (b *ResponseBuilder[T]) Meta(meta any) *ResponseBuilder[T]

Meta sets response metadata.

func (*ResponseBuilder[T]) Status

func (b *ResponseBuilder[T]) Status(code int) *ResponseBuilder[T]

Status overrides the response status code.

func (*ResponseBuilder[T]) Write

func (b *ResponseBuilder[T]) Write(w http.ResponseWriter)

Write writes the configured response.

type ValidationErrorDetail

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

ValidationErrorDetail provides structured details about a single validation error.

type Validator

type Validator interface {
	Validate(any) *ProblemDetails
}

Validator validates request payloads without coupling the core package to a validation library.

func DefaultValidator

func DefaultValidator() Validator

DefaultValidator returns the current package-level default validator.

Source Files

View all Source files