✨ 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
56
response.go
Normal file
56
response.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
package ezhandler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ResponseHelper is a simpler way to return a response.
|
||||
type ResponseHelper interface {
|
||||
// Body returns the body of the response. It is written to an [http.ResponseWriter].
|
||||
Body() (io.Reader, error)
|
||||
// Status should be a valid HTTP status.
|
||||
Status() int
|
||||
// Headers returns headers that should be added to the response.
|
||||
Headers() http.Header
|
||||
}
|
||||
|
||||
type jsonResponse struct {
|
||||
value any
|
||||
status int
|
||||
}
|
||||
|
||||
var _ ResponseHelper = new(jsonResponse)
|
||||
|
||||
func (j *jsonResponse) Body() (io.Reader, error) {
|
||||
b, err := json.Marshal(j.value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bytes.NewReader(b), nil
|
||||
}
|
||||
|
||||
func (j *jsonResponse) Status() int {
|
||||
return j.status
|
||||
}
|
||||
|
||||
func (j *jsonResponse) Headers() http.Header {
|
||||
header := make(http.Header)
|
||||
header.Set("Content-Type", "application/json")
|
||||
return header
|
||||
}
|
||||
|
||||
// JSONResponse returns a [ResponseHelper] that JSON encodes value with a 200 response.
|
||||
func JSONResponse(value any) ResponseHelper {
|
||||
return JSONResponseWithStatus(value, http.StatusOK)
|
||||
}
|
||||
|
||||
// JSONResponseWithStatus returns a [ResponseHelper] that JSON encodes value with the provided status.
|
||||
func JSONResponseWithStatus(value any, status int) ResponseHelper {
|
||||
return &jsonResponse{
|
||||
value: value,
|
||||
status: status,
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue