Add JSONBodyHandler and tests

- 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).
This commit is contained in:
Dan Jones 2025-07-08 16:04:28 -05:00
commit 5a38283bb0
2 changed files with 118 additions and 0 deletions

View file

@ -1,6 +1,7 @@
package ezhandler
import (
"encoding/json"
"io"
"net/http"
)
@ -42,3 +43,22 @@ func (fn ResponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) erro
_, 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)
}