- Implemented JSONBodyHandler for automatic JSON body parsing. - Added comprehensive unit tests for JSONBodyHandler covering successful decoding, invalid JSON, empty bodies, and error propagation. - Refactored handler_test.go to improve test structure and resolve linting issues (funlen, gocritic).
64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
package ezhandler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
// Handler is similar to [http.Handler], but also may return an error.
|
|
type Handler interface {
|
|
ServeHTTP(w http.ResponseWriter, r *http.Request) error
|
|
}
|
|
|
|
// HandlerFunc is similar to [http.HandlerFunc] but it can also return an error.
|
|
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
|
|
|
|
var _ Handler = HandlerFunc(nil)
|
|
|
|
func (fn HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
return fn(w, r)
|
|
}
|
|
|
|
// ResponseHandler is similar to HandlerFunc but returns a [ResponseHelper], instead of passing an [http.ResponseWriter].
|
|
type ResponseHandler func(r *http.Request) (resp ResponseHelper, err error)
|
|
|
|
var _ Handler = ResponseHandler(nil)
|
|
|
|
func (fn ResponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
resp, err := fn(r)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.WriteHeader(resp.Status())
|
|
for key, values := range resp.Headers() {
|
|
for _, val := range values {
|
|
w.Header().Add(key, val)
|
|
}
|
|
}
|
|
body, err := resp.Body()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = io.Copy(w, body)
|
|
return err
|
|
}
|
|
|
|
// JSONBodyHandler can be used as a [Handler] which automatically parses the json body into a value, which is passed to the function.
|
|
type JSONBodyHandler[V any] func(w http.ResponseWriter, r *http.Request, body V) error
|
|
|
|
var _ Handler = JSONBodyHandler[map[string]any](nil)
|
|
|
|
func (fn JSONBodyHandler[V]) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
|
|
reqBody := r.Body
|
|
//nolint:errcheck // This is usually fine
|
|
defer reqBody.Close()
|
|
|
|
dec := json.NewDecoder(reqBody)
|
|
var body V
|
|
if err := dec.Decode(&body); err != nil {
|
|
return err
|
|
}
|
|
|
|
return fn(w, r, body)
|
|
}
|