Documentation
¶
Overview ¶
Package m (mint) is a small, type-safe Go web toolkit built on top of net/http.
Mint does not provide a router; it relies on the standard library's http.ServeMux (Go 1.22+ enhanced patterns). The central abstraction is the H(fn) adapter, which turns a regular function into an http.HandlerFunc by automatically extracting typed parameters from the request and converting the function's return value into an HTTP response.
Index ¶
- Constants
- func Configure(opts ...Option)
- func H(fn any) http.HandlerFunc
- func Initialize(opts ...Option)
- func NewBodyReadError(err error) error
- func NewBodyTooLargeError(err error) error
- func NewEmptyBodyError() error
- func NewFileMissingError(field string) error
- func NewFormParseError(err error) error
- func NewMissingPathError(field string) error
- func NewPathConversionError(field, value, targetType string, err error) error
- func NewValidationError(err error) error
- func Reset()
- func WriteHeaders(w http.ResponseWriter, src http.Header)
- type Config
- type Cookie
- type ExtractError
- type Extractor
- type File
- type FilePart
- type Form
- type HTML
- type HTTPError
- type Header
- type JSON
- type KeySetter
- type Option
- func WithErrorHandler(handler func(w http.ResponseWriter, err error)) Option
- func WithJSONEncode(fn func(w io.Writer, v any) error) Option
- func WithJSONMarshal(fn func(v any) ([]byte, error)) Option
- func WithJSONUnmarshal(fn func(data []byte, v any) error) Option
- func WithLogger(logger *log.Logger) Option
- func WithMaxRequestBodySize(n int64) Option
- func WithSchemaDecoder(decoder *schema.Decoder) Option
- func WithValidation(enabled bool) Option
- func WithValidator(v *validator.Validate) Option
- type Path
- type PathValue
- type Query
- type Responder
- type ResponseWriter
- func (rw *ResponseWriter) Flush()
- func (rw *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (rw *ResponseWriter) Push(target string, opts *http.PushOptions) error
- func (rw *ResponseWriter) Status() int
- func (rw *ResponseWriter) Unwrap() http.ResponseWriter
- func (rw *ResponseWriter) Write(b []byte) (int, error)
- func (rw *ResponseWriter) WriteHeader(code int)
- func (rw *ResponseWriter) Written() bool
- type Result
- type StatusCode
Constants ¶
const ( ErrTypeBodyRead = "body_read_error" ErrTypeBodyTooLarge = "body_too_large" ErrTypeEmptyBody = "empty_body" ErrTypeFormParse = "form_parse_error" ErrTypeFileMissing = "file_missing" ErrTypePathConversion = "path_conversion_error" ErrTypeMissingPath = "missing_path_value" ErrTypeValidation = "validation_error" )
ExtractError type names (used by toHTTPError to decide the HTTP status).
const DefaultMaxRequestBodySize int64 = 5 << 20
DefaultMaxRequestBodySize is the default request-body cap (5 MiB). It applies to all extractors that read the body (JSON, Form). Override with WithMaxRequestBodySize. Set to <= 0 to disable.
const DefaultMultipartMemory int64 = 32 << 20
DefaultMultipartMemory is the in-memory budget passed to Request.ParseMultipartForm. File content beyond this threshold is stored in temporary files by the standard library.
Variables ¶
This section is empty.
Functions ¶
func Configure ¶ added in v0.4.0
func Configure(opts ...Option)
Configure updates the configuration. Unlike Initialize, it may be called multiple times and is safe for runtime tweaks.
func H ¶
func H(fn any) http.HandlerFunc
H adapts fn into an http.HandlerFunc.
The handler may have zero or more parameters; each parameter must be one of:
- *http.Request
- http.ResponseWriter
- a value type whose pointer implements Extractor
It may return zero, one, or two values:
- 0 values → empty 200 response
- 1 value → see "Response Types" in the README
- 2 values → (T, error) where T is a struct/scalar/http.Handler/io.Reader/Responder
Misuse panics at registration time so problems surface before the server starts serving traffic.
func Initialize ¶ added in v0.4.0
func Initialize(opts ...Option)
Initialize installs configuration once at application startup. The first call wins; subsequent calls are ignored and emit a warning via the active logger. Use Configure for runtime updates and Reset for tests.
func NewBodyReadError ¶
func NewBodyTooLargeError ¶ added in v1.0.0
NewBodyTooLargeError wraps an http.MaxBytesError.
func NewEmptyBodyError ¶
func NewEmptyBodyError() error
func NewFileMissingError ¶ added in v1.1.0
func NewFormParseError ¶
func NewMissingPathError ¶
func NewPathConversionError ¶
func NewValidationError ¶ added in v0.3.0
func Reset ¶ added in v0.4.0
func Reset()
Reset restores defaults and clears the one-shot Initialize flag. Intended for use in tests.
func WriteHeaders ¶
func WriteHeaders(w http.ResponseWriter, src http.Header)
WriteHeaders adds every (key, value) pair from src to w.Header().
Types ¶
type Config ¶
type Config struct {
// SchemaDecoder decodes URL query and form values into structs.
SchemaDecoder *schema.Decoder
// JSONMarshalFunc serializes a value to JSON bytes. When set, it takes
// precedence over the default streaming encoder. Setting it via
// WithJSONMarshal clears JSONEncodeFunc so the two never conflict.
JSONMarshalFunc func(v any) ([]byte, error)
// JSONEncodeFunc streams a value as JSON. Used in preference to
// JSONMarshalFunc when both happen to be set.
JSONEncodeFunc func(w io.Writer, v any) error
// JSONUnmarshalFunc decodes JSON bytes into a value.
JSONUnmarshalFunc func(data []byte, v any) error
// Logger is used for warnings and 5xx error logs.
Logger *log.Logger
// EnableValidation toggles automatic struct validation in JSON, Query,
// Form, Header and Cookie extractors.
EnableValidation bool
// Validator is the validation engine. Auto-created if nil and
// EnableValidation is true.
Validator *validator.Validate
// ErrorHandler, when non-nil, replaces the default JSON error response.
// Receives the (possibly wrapped) ResponseWriter and the error.
ErrorHandler func(w http.ResponseWriter, err error)
// MaxRequestBodySize caps the number of bytes read from r.Body in body
// consuming extractors (JSON, Form). Defaults to DefaultMaxRequestBodySize.
// Set to <= 0 to disable.
MaxRequestBodySize int64
}
Config holds the framework's global configuration.
All fields are optional; defaultConfig() supplies safe defaults.
type Cookie ¶ added in v1.0.0
type Cookie[T any] struct { Value T }
Cookie[T] reads request cookies into a struct. Each exported field is bound by an optional `cookie:"name"` tag (defaulting to the field name). Missing cookies leave fields at their zero value.
type ExtractError ¶
ExtractError reports a failure inside an Extractor. The Type field drives the HTTP status mapping in toHTTPError.
func (*ExtractError) Error ¶
func (e *ExtractError) Error() string
func (*ExtractError) Unwrap ¶
func (e *ExtractError) Unwrap() error
type Extractor ¶
Extractor is implemented by types that pull data out of *http.Request. User-defined extractors should implement Extract on a pointer receiver.
type File ¶ added in v1.1.0
type File struct {
Value FilePart
}
File extracts the first uploaded file from a multipart/form-data request. For name-based file binding, use FilePart fields inside Form[T].
type FilePart ¶ added in v1.1.0
type FilePart struct {
Name string
Filename string
ContentType string
Size int64
// contains filtered or unexported fields
}
FilePart is a multipart file part extracted from a request.
The underlying file stream is opened lazily by Open or Save. It can be consumed only once.
func (*FilePart) Consumed ¶ added in v1.1.0
Consumed reports whether Open or Save has consumed this file part.
type Form ¶
type Form[T any] struct { Value T }
Form[T] parses URL-encoded or multipart form data and decodes r.Form into T using the schema decoder. In multipart requests, FilePart fields are bound from file parts by their schema/form tag name.
type HTTPError ¶
type HTTPError struct {
Code int `json:"code"`
Err string `json:"error"`
Message string `json:"message,omitempty"`
}
HTTPError is the canonical, JSON-encodable error type. Return one from a handler to control the exact status code, error tag, and (optional) message.
type Header ¶ added in v1.0.0
type Header[T any] struct { Value T }
Header[T] reads request headers into a struct. Each exported field is bound by an optional `header:"X-My-Name"` tag (defaulting to the field name). Missing headers leave fields at their zero value.
Only scalar types are supported on fields (string/int/uint/float/bool and their named variants). Validation runs after extraction.
type JSON ¶
type JSON[T any] struct { Value T }
JSON[T] reads a JSON-encoded request body, unmarshals it into T, then validates if validation is enabled.
type KeySetter ¶
type KeySetter interface {
SetKey(string)
}
KeySetter is implemented by extractors whose binding name (e.g. a path parameter) is decided by H() at request time.
type Option ¶ added in v0.4.0
type Option func(*Config)
Option is a functional option for configuring the framework.
func WithErrorHandler ¶ added in v0.4.0
func WithErrorHandler(handler func(w http.ResponseWriter, err error)) Option
WithErrorHandler installs a custom error handler.
func WithJSONEncode ¶ added in v0.4.0
WithJSONEncode installs a custom streaming JSON encoder.
func WithJSONMarshal ¶ added in v0.4.0
WithJSONMarshal installs a custom JSON marshaling function. This clears any previously set JSONEncodeFunc so behavior is unambiguous.
func WithJSONUnmarshal ¶ added in v0.4.0
WithJSONUnmarshal installs a custom JSON unmarshaling function.
func WithLogger ¶ added in v0.4.0
WithLogger installs a custom *log.Logger.
func WithMaxRequestBodySize ¶ added in v1.0.0
WithMaxRequestBodySize sets the maximum request body size in bytes. A value <= 0 disables the limit.
func WithSchemaDecoder ¶ added in v0.4.0
WithSchemaDecoder installs a custom gorilla/schema decoder for query/form.
func WithValidation ¶ added in v0.4.0
WithValidation toggles request validation globally.
func WithValidator ¶ added in v0.4.0
WithValidator installs a custom validator.
type Path ¶
type Path[T PathValue] struct { Value T // contains filtered or unexported fields }
Path[T] extracts a single path parameter from r.PathValue. The binding name is set by H() based on positional order of Path[T] parameters in the handler signature; see README "Pitfalls" for the implications.
type Query ¶
type Query[T any] struct { Value T }
Query[T] decodes r.URL.Query() into T using the schema decoder.
type Responder ¶
type Responder interface {
Respond(w http.ResponseWriter)
}
Responder lets a return type fully control how it's written to the response.
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter wraps http.ResponseWriter so the framework can observe and guard the response state (track header writes, prevent double WriteHeader, expose the underlying writer via Unwrap and the standard optional interfaces: Flusher, Hijacker, Pusher).
func (*ResponseWriter) Flush ¶ added in v1.0.0
func (rw *ResponseWriter) Flush()
Flush implements http.Flusher when the underlying writer supports it. Safe to call otherwise (it becomes a no-op), so SSE handlers don't have to type-assert before flushing.
func (*ResponseWriter) Hijack ¶ added in v1.0.0
func (rw *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements http.Hijacker when the underlying writer supports it.
func (*ResponseWriter) Push ¶ added in v1.0.0
func (rw *ResponseWriter) Push(target string, opts *http.PushOptions) error
Push implements http.Pusher when the underlying writer supports it.
func (*ResponseWriter) Status ¶ added in v1.0.0
func (rw *ResponseWriter) Status() int
Status returns the status code that was written, or 0 if none.
func (*ResponseWriter) Unwrap ¶ added in v1.0.0
func (rw *ResponseWriter) Unwrap() http.ResponseWriter
Unwrap returns the underlying http.ResponseWriter so callers (including http.NewResponseController) can reach optional interfaces directly.
func (*ResponseWriter) WriteHeader ¶
func (rw *ResponseWriter) WriteHeader(code int)
func (*ResponseWriter) Written ¶ added in v1.0.0
func (rw *ResponseWriter) Written() bool
Written reports whether headers have been sent to the client.
type Result ¶
Result is the most flexible return type: pick a status code, set response headers, and either set Data (success) or Err (failure).
type StatusCode ¶
type StatusCode int
StatusCode is a numeric return value that sets the response status with an empty body. Useful for 201, 202, 204, etc.