rest

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package rest is a tiny typed-handler layer over net/http. A HandlerFunc returns an Encoder (a value that knows how to serialize itself) instead of writing to the ResponseWriter directly, which makes handlers easy to test and keeps response encoding and error handling in one place.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(r *http.Request, v any) error

Decode reads a JSON request body into v and validates it with errs.Check. It returns an *errs.Error (InvalidArgument) on malformed input.

func Respond

func Respond(ctx context.Context, w http.ResponseWriter, resp Encoder) error

Respond writes resp to w. A nil Encoder yields 204 No Content. If encoding fails, a 500 with a generic error body is written instead.

Types

type Encoder

type Encoder interface {
	Encode() (data []byte, contentType string, err error)
}

Encoder is a value that can serialize itself into a response body.

func JSON

func JSON(v any) Encoder

JSON wraps v as a JSON Encoder with status 200.

func JSONStatus

func JSONStatus(v any, status int) Encoder

JSONStatus wraps v as a JSON Encoder with an explicit status.

type HandlerFunc

type HandlerFunc func(ctx context.Context, r *http.Request) Encoder

HandlerFunc handles a request and returns an Encoder describing the response. Returning a non-nil error value (e.g. *errs.Error) is the idiomatic way to signal failure — Respond will set the right status.

func ChainMiddleware

func ChainMiddleware(h HandlerFunc, mw ...MidFunc) HandlerFunc

ChainMiddleware wraps h with mw in order, so mw[0] is the outermost layer.

type MidFunc

type MidFunc func(HandlerFunc) HandlerFunc

MidFunc wraps a HandlerFunc to add cross-cutting behavior.

Jump to

Keyboard shortcuts

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