✨ 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.
This commit is contained in:
parent
a136616088
commit
1c16a893d6
5 changed files with 270 additions and 1 deletions
33
handler.go
33
handler.go
|
|
@ -1,13 +1,44 @@
|
|||
package ezhandler
|
||||
|
||||
import "net/http"
|
||||
import (
|
||||
"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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue