ezhandler/helper.go
Dan Jones 1c16a893d6 Refactor ResponseHelper and add ResponderHandler
- Modified ResponseHelper.Body signature to return an io.Reader and an error.
- Updated ResponseHandler.ServeHTTP to handle errors from ResponseHelper.Body.
- Implemented JSONResponse and JSONResponseWithStatus functions for easier JSON responses.
- Added comprehensive unit tests for JSON response handling, including error scenarios.
- Extended Helper.ResponderHandler with a new test case to ensure proper error handling and response generation.
- Resolved linting issues related to dynamic error definition and function length in tests.
2025-07-08 09:12:53 -05:00

42 lines
1.4 KiB
Go

package ezhandler
import "net/http"
func NewHelper(errH ErrorHandler) *Helper {
return &Helper{errH}
}
// ErrorHandler writes an appropriate response to the [http.ResponseWriter] for the provided [error].
// If the [error] is nil, it should be a no op.
type ErrorHandler func(http.ResponseWriter, *http.Request, error)
// Helper provides methods to make easier, more idiomatic [http.Handler]s.
type Helper struct {
errHandler ErrorHandler
}
// Handler returns an [http.Handler] for the provided [Handler].
// If hnd returns an error, an appropriate error response is written using the ErrorHandler.
func (help *Helper) Handler(hnd Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := hnd.ServeHTTP(w, r); err != nil {
help.errHandler(w, r, err)
}
})
}
// Handler returns an [http.Handler] for the provided [HandlerFunc].
// If hnd returns an error, an appropriate error response is written using the ErrorHandler.
func (help *Helper) HandlerFunc(hnd HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := hnd(w, r); err != nil {
help.errHandler(w, r, err)
}
})
}
// ResponderHandler returns an [http.Handler] for the provided [ResponderHandler].
// If hnd returns an error, an appropriate error response is written using the ErrorHandler.
func (help *Helper) ResponderHandler(hnd ResponseHandler) http.Handler {
return help.Handler(hnd)
}