-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.go
39 lines (33 loc) · 984 Bytes
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package httpwrap
import (
"encoding/json"
"io"
)
// HTTPResponse is used by the StandardResponseWriter to construct the
// response body according to the StatusCode() and WriteBody() functions.
// If the StatusCode() function returns `0`, the StandardResponseWriter will
// assume that WriteHeader has already been called on the http.ResponseWriter
// object.
type HTTPResponse interface {
StatusCode() int
WriteBody(io.Writer) error
}
// The jsonResponse type implements HTTPResponse. When returned, it will
// write the status code in the http response's header and JSON encode the
// body.
type jsonResponse struct {
code int
body any
}
func NewJSONResponse(code int, body any) HTTPResponse {
return jsonResponse{
code: code,
body: body,
}
}
func (res jsonResponse) StatusCode() int { return res.code }
func (res jsonResponse) WriteBody(writer io.Writer) error {
encoder := json.NewEncoder(writer)
encoder.SetIndent("", " ")
return encoder.Encode(res.body)
}