m

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 22 Imported by: 0

README

Mint

A small, type-safe Go web toolkit built on top of net/http.

Mint is not a framework. It does not give you a router, a middleware chain, or a request context type. What it gives you is one thing: a way to write HTTP handlers as plain, type-safe Go functions.

func GetUser(id m.Path[int]) (User, error) { ... }
func CreateUser(body m.JSON[NewUser]) m.Result[User] { ... }
func Search(q m.Query[Filter]) []Result { ... }

You keep http.ServeMux. You keep http.HandlerFunc. Mint is a thin adapter in between that does parameter extraction, validation, and response serialization for you — and gets out of the way for everything else.

go get github.com/cymoo/mint

Requires Go 1.23+ (for the enhanced routing patterns in net/http).


Table of Contents


Hello, Mint

package main

import (
    "net/http"

    m "github.com/cymoo/mint"
)

func hello(name m.Query[struct {
    Name string `schema:"name"`
}]) string {
    if name.Value.Name == "" {
        return "Hello, world!"
    }
    return "Hello, " + name.Value.Name + "!"
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /hello", m.H(hello))
    http.ListenAndServe(":8080", mux)
}

That's it. No Engine, no Router, no app := mint.New().


Core idea: H(handler)

m.H adapts any function whose parameters and return values Mint understands into an http.HandlerFunc:

http.HandleFunc(pattern, m.H(yourFunc))
Allowed parameters
Parameter type What it gives you
m.JSON[T] Decoded + validated JSON body
m.Query[T] Decoded + validated query string
m.Form[T] Decoded + validated form (application/x-www-form-urlencoded or multipart/form-data)
m.File First uploaded file from a multipart form
m.Path[T] A single typed path parameter
m.Header[T] Headers mapped onto a struct via header tags
m.Cookie[T] Cookies mapped onto a struct via cookie tags
http.ResponseWriter The raw writer (wrapped, see below)
*http.Request The raw request
any type implementing Extractor Your own extractor

Mint panics at registration time if you use anything else as a parameter. Bad handlers blow up at startup, not at request time.

Allowed return shapes
Return Behavior
none 200, empty body
T JSON-encoded (or special-cased below)
error Error pipeline (see Errors)
(T, error) Common case: data on success, error on failure
m.Result[T] Full control: code, headers, body, or error
m.StatusCode Empty body with this status
m.HTML Content-Type: text/html
[]byte Content-Type: application/octet-stream
io.Reader Streamed verbatim
http.Handler Delegated to
any type implementing Responder Calls Respond(w, r)

Any other concrete type is JSON-encoded. The first value of (T, error) cannot be Result[U] — pick one style or the other.


Extracting input

All extractors are tiny generic wrappers. Their decoded value lives in .Value.

JSON[T]
type CreateUser struct {
    Name  string `json:"name"  validate:"required,min=2"`
    Email string `json:"email" validate:"required,email"`
}

func createUser(body m.JSON[CreateUser]) (User, error) {
    return saveUser(body.Value), nil
}
  • Body is automatically size-limited (default 5 MiB; configurable).
  • Empty body → empty_body error.
  • Malformed JSON → 400 with Err: "json_decode_error".
  • Validation tags are honored.
Query[T]
type Filter struct {
    Page  int    `schema:"page"  validate:"gte=1"`
    Limit int    `schema:"limit" validate:"gte=1,lte=100"`
    Q     string `schema:"q"`
}

func search(f m.Query[Filter]) []Hit { ... }

Query strings are decoded with gorilla/schema using schema tags.

Form[T]
type Login struct {
    Username string `schema:"username" validate:"required"`
    Password string `schema:"password" validate:"required,min=8"`
}

func login(f m.Form[Login]) error { ... }

Same conventions as Query[T], but reads r.Form after parsing URL-encoded or multipart form data.

Multipart file fields can be bound by schema/form tag to m.FilePart, *m.FilePart, []m.FilePart, or []*m.FilePart:

type Upload struct {
    Title string     `schema:"title"`
    File  m.FilePart `schema:"file"`
}

func upload(f m.Form[Upload]) error {
    name := filepath.Base(f.Value.File.Filename)
    return f.Value.File.Save(filepath.Join("./uploads", name))
}

FilePart.Save(path) streams the upload to disk, creates parent directories, removes a partial target on failure, and can only be called once. Use FilePart.Open() if you need to stream the file yourself.

File
func upload(file m.File) error {
    name := filepath.Base(file.Value.Filename)
    return file.Save(filepath.Join("./uploads", name))
}

File extracts the first uploaded file from a multipart/form-data request. Use Form[T] with FilePart fields when you need to bind a specific form field name or accept multiple files.

Path[T]

Path[T] extracts a single typed path parameter:

mux.HandleFunc("GET /users/{id}", m.H(func(id m.Path[int]) User { ... }))
mux.HandleFunc("GET /files/{name}", m.H(func(name m.Path[string]) File { ... }))

Supported types: string, int, int8, int16, int32, int64, uintuint64, float32, float64, bool.

⚠️ Path binding is positional, not by name. Path params are matched to handler parameters in order. For mux.HandleFunc("GET /users/{uid}/posts/{pid}", m.H(handler)), the first Path[T] parameter in handler receives {uid}, the second receives {pid} — regardless of the Go variable names you choose.

// pid gets {uid}, uid gets {pid}. Don't do this:
func bad(pid m.Path[int], uid m.Path[int]) { ... }

// Match argument order to URL order:
func good(uid m.Path[int], pid m.Path[int]) { ... }

If you declare more Path[T] parameters than the route pattern provides, Mint returns 400 at request time (and logs a one-time warning).

Header[T]
type AuthHeaders struct {
    Token     string `header:"Authorization" validate:"required"`
    RequestID string `header:"X-Request-ID"`
}

func protected(h m.Header[AuthHeaders]) string {
    return "hello, " + h.Value.Token
}

Missing headers are zero values. Use validate:"required" if you need them present.

type Session struct {
    ID    string `cookie:"session_id" validate:"required"`
    Theme string `cookie:"theme"`
}

func me(s m.Cookie[Session]) User { ... }
Raw access

You can mix extractors with http.ResponseWriter and *http.Request freely:

func download(id m.Path[int], w http.ResponseWriter, r *http.Request) error {
    f, err := openFile(id.Value)
    if err != nil { return err }
    defer f.Close()
    http.ServeContent(w, r, f.Name(), f.ModTime(), f)
    return nil
}
Custom extractors

Any type that implements Extract(*http.Request) error (on a pointer receiver) works:

type Authed struct{ User User }

func (a *Authed) Extract(r *http.Request) error {
    u, err := userFromBearer(r.Header.Get("Authorization"))
    if err != nil { return &m.HTTPError{Code: 401, Err: "unauthorized"} }
    a.User = u
    return nil
}

func me(a Authed) User { return a.User }

Returning output

The most common pattern is (T, error):

func getUser(id m.Path[int]) (User, error) {
    u, ok := users[id.Value]
    if !ok {
        return User{}, &m.HTTPError{Code: 404, Err: "not_found"}
    }
    return u, nil
}

When you need to control the status code or headers, use Result[T]:

func createUser(body m.JSON[NewUser]) m.Result[User] {
    u := save(body.Value)
    return m.Result[User]{
        Code: 201,
        Headers: http.Header{
            "Location": {fmt.Sprintf("/users/%d", u.ID)},
        },
        Data: u,
    }
}

There are helpers m.OK[T](data) and m.Err[T](code, err) for trivial cases.

Special return types
func deleted() m.StatusCode { return 204 }
func page() m.HTML          { return "<h1>Hi</h1>" }
func csv() []byte           { return []byte("a,b,c\n") }
func bigFile() io.Reader    { f, _ := os.Open("x"); return f }

Errors

Mint converts errors into HTTP responses in this order of priority:

  1. *HTTPError — used verbatim.

    return &m.HTTPError{Code: 404, Err: "not_found", Message: "user 42 not found"}
    
  2. *ExtractError — emitted by built-in/custom extractors. Mint maps the Type to a code (body_too_large → 413, etc.).

  3. Anything else — Mint inspects the error message to guess a status:

    • "not found" / "doesn't exist" → 404
    • "unauthorized" / "auth" → 401
    • "forbidden" → 403
    • "timeout" → 408
    • "conflict" / "exists" → 409
    • "invalid" / "validation" → 400
    • otherwise → 500
Visibility rules
Status range Message in response body Logged?
4xx Yes — set to err.Error() No
5xx Hidden (empty) Yes (mint: 5xx)

This way internal errors don't leak to clients, but you still see them in logs.

If you want exact control: return *HTTPError. Mint will respect both Err and Message regardless of code.


Validation

Validation is on by default and uses go-playground/validator. The framework wires up tag-name lookup for json, schema, header, and cookie tags so error messages reference the input name, not the Go field name.

type Body struct {
    Email string `json:"email" validate:"required,email"`
}

// On bad input:
// 400 {"err":"validation_failed","message":"email: required validation failed"}

Turn it off with m.Configure(m.WithValidation(false)) or use a custom validator with m.WithValidator(...).


Streaming, SSE, hijack

The ResponseWriter that handlers receive is a thin wrapper that still forwards to the underlying http.ResponseWriter. It explicitly implements:

  • http.Flusher — for SSE / text/event-stream
  • http.Hijacker — for protocol upgrades (WebSocket, etc.)
  • http.Pusher — for HTTP/2 push

Each delegates to the underlying writer, or returns http.ErrNotSupported if the underlying server doesn't support it.

func sse(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    flusher, _ := w.(http.Flusher)
    for i := 0; i < 5; i++ {
        fmt.Fprintf(w, "data: tick %d\n\n", i)
        flusher.Flush()
        time.Sleep(time.Second)
    }
}

Configuration

Configuration is global and thread-safe. Set it once at startup:

m.Initialize(
    m.WithMaxRequestBodySize(10 << 20), // 10 MiB
    m.WithLogger(myLogger),
)

Initialize should be called at most once. Use Configure to override later (e.g. in tests). Reset returns everything to defaults.

Option Default
WithMaxRequestBodySize(n) 5 << 20 (5 MiB). Pass 0 to disable.
WithJSONEncode(fn) json.Encoder with SetEscapeHTML(false)
WithJSONMarshal(fn) (unset; falls back to encoder)
WithJSONUnmarshal(fn) json.Unmarshal
WithSchemaDecoder(d) schema.Decoder with IgnoreUnknownKeys(true)
WithValidation(bool) true
WithValidator(v) auto-created when validation enabled
WithLogger(l) log.Default()
WithErrorHandler(fn) built-in (returns JSON HTTPError)

Pitfalls & limitations

A short, honest list of things that will bite you if you don't know them.

1. Path[T] binds positionally, not by name. See the Path[T] section. The order of Path[T] parameters in your function must match the left-to-right order of {name} in the URL pattern. The Go variable names are ignored.

2. Request body is capped at 5 MiB by default. JSON and form bodies above the limit get 413 {"err":"body_too_large"}. Configure with m.WithMaxRequestBodySize(n). Set to 0 to disable (not recommended).

3. 5xx error messages are hidden from clients by default. Generic errors with a 5xx-mapped status produce a body without Message. The full error is logged. Return an *HTTPError if you intentionally want the message in the response.

4. JSON output does not escape <, >, & by default. Mint's default encoder calls json.Encoder.SetEscapeHTML(false). If you embed user-controlled JSON inside an HTML page, escape it yourself. Restore the standard behavior with m.WithJSONMarshal(json.Marshal).

5. Configuration is global. Calling Configure from multiple goroutines is safe, but it affects every request. Don't tweak it per-request.

6. Initialize should be called once. A second call is ignored — Mint will log a warning telling you so. Use Configure to layer further changes, or Reset (in tests).

7. ResponseWriter is wrapped. Type-asserting to your own custom interface won't work. Use http.NewResponseController(w) or the explicit methods Mint exposes (Flush, Hijack, Push). Call Unwrap() if you need the raw writer.

8. Handler signatures are checked at registration, not compile time. A bad signature passed to m.H panics when H runs. Register all routes at startup so problems surface immediately.


What Mint does not do

By design:

  • No router. Use http.ServeMux (Go 1.22+ patterns) or anything else that produces http.HandlerFunc.
  • No middleware system. Use func(http.Handler) http.Handler middleware — Mint's adapter is itself just an http.HandlerFunc.
  • No request context wrapper. Use r.Context().
  • No DI container, no app object, no global state beyond config.

If you want any of these, pick a heavier framework. If you want plain Go with less boilerplate, Mint is for you.


License

MIT — see LICENSE.

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

View Source
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).

View Source
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.

View Source
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 NewBodyReadError(err error) error

func NewBodyTooLargeError added in v1.0.0

func NewBodyTooLargeError(err error) error

NewBodyTooLargeError wraps an http.MaxBytesError.

func NewEmptyBodyError

func NewEmptyBodyError() error

func NewFileMissingError added in v1.1.0

func NewFileMissingError(field string) error

func NewFormParseError

func NewFormParseError(err error) error

func NewMissingPathError

func NewMissingPathError(field string) error

func NewPathConversionError

func NewPathConversionError(field, value, targetType string, err error) error

func NewValidationError added in v0.3.0

func NewValidationError(err error) error

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[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.

func (*Cookie[T]) Extract added in v1.0.0

func (c *Cookie[T]) Extract(r *http.Request) error

type ExtractError

type ExtractError struct {
	Type    string
	Field   string
	Value   string
	Message string
	Err     error
}

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

type Extractor interface {
	Extract(*http.Request) error
}

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].

func (*File) Extract added in v1.1.0

func (f *File) Extract(r *http.Request) error

func (*File) Open added in v1.1.0

func (f *File) Open() (multipart.File, error)

Open is a convenience wrapper around f.Value.Open.

func (*File) Save added in v1.1.0

func (f *File) Save(path string) error

Save is a convenience wrapper around f.Value.Save.

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

func (p *FilePart) Consumed() bool

Consumed reports whether Open or Save has consumed this file part.

func (*FilePart) Open added in v1.1.0

func (p *FilePart) Open() (multipart.File, error)

Open opens the uploaded file for streaming. The returned file must be closed. Open and Save share the same one-shot consumption guard.

func (*FilePart) Save added in v1.1.0

func (p *FilePart) Save(path string) (err error)

Save streams the uploaded file to path. It creates parent directories as needed and removes the target if copying or closing fails.

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.

func (*Form[T]) Extract

func (f *Form[T]) Extract(r *http.Request) error

type HTML

type HTML string

HTML is a string typed so the framework serves it as text/html.

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.

func (HTTPError) Error

func (e HTTPError) Error() string
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.

func (*Header[T]) Extract added in v1.0.0

func (h *Header[T]) Extract(r *http.Request) error

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.

func (*JSON[T]) Extract

func (j *JSON[T]) Extract(r *http.Request) error

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

func WithJSONEncode(fn func(w io.Writer, v any) error) Option

WithJSONEncode installs a custom streaming JSON encoder.

func WithJSONMarshal added in v0.4.0

func WithJSONMarshal(fn func(v any) ([]byte, error)) Option

WithJSONMarshal installs a custom JSON marshaling function. This clears any previously set JSONEncodeFunc so behavior is unambiguous.

func WithJSONUnmarshal added in v0.4.0

func WithJSONUnmarshal(fn func(data []byte, v any) error) Option

WithJSONUnmarshal installs a custom JSON unmarshaling function.

func WithLogger added in v0.4.0

func WithLogger(logger *log.Logger) Option

WithLogger installs a custom *log.Logger.

func WithMaxRequestBodySize added in v1.0.0

func WithMaxRequestBodySize(n int64) Option

WithMaxRequestBodySize sets the maximum request body size in bytes. A value <= 0 disables the limit.

func WithSchemaDecoder added in v0.4.0

func WithSchemaDecoder(decoder *schema.Decoder) Option

WithSchemaDecoder installs a custom gorilla/schema decoder for query/form.

func WithValidation added in v0.4.0

func WithValidation(enabled bool) Option

WithValidation toggles request validation globally.

func WithValidator added in v0.4.0

func WithValidator(v *validator.Validate) Option

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.

func (*Path[T]) Extract

func (p *Path[T]) Extract(r *http.Request) error

func (*Path[T]) Key

func (p *Path[T]) Key() string

Key returns the path-parameter name this extractor is bound to. Useful for debugging and custom error reporting.

func (*Path[T]) SetKey

func (p *Path[T]) SetKey(key string)

SetKey is invoked by the framework. Manually calling it before H() invokes the extractor (e.g., in unit tests for an extractor in isolation) is fine.

type PathValue

type PathValue interface {
	~string | ~int | ~int64 | ~uint | ~uint64 | ~float64 | ~bool
}

PathValue lists the scalar Go types supported by Path[T].

type Query

type Query[T any] struct {
	Value T
}

Query[T] decodes r.URL.Query() into T using the schema decoder.

func (*Query[T]) Extract

func (q *Query[T]) Extract(r *http.Request) error

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) Write

func (rw *ResponseWriter) Write(b []byte) (int, error)

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

type Result[T any] struct {
	Code    int
	Headers http.Header

	Data T
	Err  error
}

Result is the most flexible return type: pick a status code, set response headers, and either set Data (success) or Err (failure).

func Err

func Err[T any](code int, err error) Result[T]

Err returns an error Result with the given status code and error.

func OK

func OK[T any](data T) Result[T]

OK returns a successful Result with the given Data and no explicit Code (which becomes 200 when written).

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.

Directories

Path Synopsis
Package main is a runnable tour of every Mint feature.
Package main is a runnable tour of every Mint feature.

Jump to

Keyboard shortcuts

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