Bind and BindEmpty fill Req from path/query/json struct tags and validate once, extending the typed decode->validate->call->encode pipeline to routes with identifiers and filters. Conversion via builtins + encoding.TextUnmarshaler (uuid.UUID, time.Time); malformed value -> 400 naming the parameter; default: applies only when absent; repeated query -> slice; mis-tagged struct panics at wiring. Purely additive; existing adapters unchanged. Coordinated lockstep v1.6.0.
27 lines
1.1 KiB
Go
27 lines
1.1 KiB
Go
package httputil
|
|
|
|
import "net/http"
|
|
|
|
var _ http.Handler = HandlerFunc(nil)
|
|
|
|
// HandlerFunc is an http.Handler that returns an error.
|
|
// On non-nil error the error is mapped to the appropriate HTTP response via [Error].
|
|
//
|
|
// Use it for genuinely custom responses — streaming, file downloads, non-JSON
|
|
// content types — where the typed adapters do not fit. It is no longer the answer
|
|
// for path or query parameters: [Bind] and [BindEmpty] fill those from struct tags
|
|
// with the same decode → validate → encode guarantees, and a custom success status
|
|
// is set with [WithStatus]. Reaching for HandlerFunc to read a parameter is the one
|
|
// path by which a handler reaches production without validation running.
|
|
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
|
|
|
|
// ServeHTTP implements http.Handler.
|
|
// Errors are written as standardized JSON without logging — no logger is in
|
|
// scope for a bare function type. Use [Handle], [HandleNoBody], or
|
|
// [HandleEmpty] for centralized logging, or call [Error] explicitly.
|
|
func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if err := h(w, r); err != nil {
|
|
writeError(w, err)
|
|
}
|
|
}
|