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