Add JSONResponder type and tests

- Introduced JSONResponder type in handler.go, combining JSON body parsing with ResponseHelper handling.
- Implemented ServeHTTP for JSONResponder to automatically decode JSON requests and return structured responses.
- Added comprehensive unit tests for JSONResponder in handler_test.go, covering successful responses, invalid JSON, empty bodies, and error propagation.
- Ensured all new tests adhere to existing project conventions and pass linting checks.
This commit is contained in:
Dan Jones 2025-07-08 16:41:08 -05:00
commit fe7e464a62
2 changed files with 102 additions and 0 deletions

View file

@ -62,3 +62,27 @@ func (fn JSONBodyHandler[V]) ServeHTTP(w http.ResponseWriter, r *http.Request) e
return fn(w, r, body)
}
// JSONResponder can be used as a [Handler] which automatically parses the json body into a value, which is passed to the function.
// It also returns a [ResponseHelper], instead of passing an [http.ResponseWriter].
type JSONResponder[V any] func(r *http.Request, body V) (ResponseHelper, error)
var _ Handler = JSONResponder[map[string]any](nil)
func (fn JSONResponder[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
}
var rh ResponseHandler = func(req *http.Request) (ResponseHelper, error) {
return fn(req, body)
}
return rh.ServeHTTP(w, r)
}