blob: 88d067062fdc03431e3b98ecd2ce3a985622ddb0 [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
iomodo493dd482021-04-02 00:07:51 +040026 w.WriteHeader(statusCode)
iomodoa19d4792021-03-26 00:27:25 +040027
28 encoder := json.NewEncoder(w)
29 encoder.SetEscapeHTML(true)
30 encoder.SetIndent("", "")
31
32 if err := encoder.Encode(payload); err != nil {
33 return err
34 }
35
iomodoa19d4792021-03-26 00:27:25 +040036 return nil
37}