ezhandler/response.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

56 lines
1.3 KiB
Go

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,
}
}