blob: dbc5882eb2946a498e694c00b6e38965db618b7f [file] [log] [blame]
iomodoa19d4792021-03-26 00:27:25 +04001package rest
2
3import (
4 "encoding/json"
5 "net/http"
6)
7
8type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
9
10// ServeHTTP calls f(w, r) and handles error
11func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
12 if err := f(w, r); err != nil {
13 jsoner(w, http.StatusBadRequest, err.Error()) // TODO detect the correct statusCode from error
14 }
15}
16
17func jsoner(w http.ResponseWriter, statusCode int, payload interface{}) error {
18 w.Header().Set("Content-Type", "application/json")
19
20 // If there is nothing to marshal then set status code and return.
21 if payload == nil {
22 _, err := w.Write([]byte("{}"))
23 return err
24 }
25
26 if statusCode != http.StatusOK {
27 w.WriteHeader(statusCode)
28 }
29
30 encoder := json.NewEncoder(w)
31 encoder.SetEscapeHTML(true)
32 encoder.SetIndent("", "")
33
34 if err := encoder.Encode(payload); err != nil {
35 return err
36 }
37
38 if f, ok := w.(http.Flusher); ok {
39 f.Flush()
40 }
41
42 return nil
43}