-
Notifications
You must be signed in to change notification settings - Fork 2
/
render.go
31 lines (25 loc) · 828 Bytes
/
render.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
package hook
import (
"encoding/json"
"net/http"
"github.com/alexisvisco/kcd/pkg/errors"
"github.com/alexisvisco/kcd/internal/kcderr"
)
// Render is the default render hook.
// It marshals the output into JSON, or returns an empty body if the payload is nil.
func Render(w http.ResponseWriter, _ *http.Request, response interface{}, statusCode int) error {
if response != nil {
marshal, err := json.Marshal(response)
if err != nil {
return errors.Wrap(err, "unable to render response in json format").WithKind(kcderr.OutputCritical)
}
w.Header().Set("Content-type", "application/json")
w.WriteHeader(statusCode)
if _, err := w.Write(marshal); err != nil {
return errors.Wrap(err, "unable to write response").WithKind(kcderr.OutputCritical)
}
} else {
w.WriteHeader(statusCode)
}
return nil
}