Files
web/httputil/handler_func.go
T

27 lines
1.1 KiB
Go
Raw Permalink Normal View History

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