| iomodo | a19d479 | 2021-03-26 00:27:25 +0400 | [diff] [blame] | 1 | package rest |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "net/http" |
| 6 | ) |
| 7 | |
| 8 | type HandlerFunc func(w http.ResponseWriter, r *http.Request) error |
| 9 | |
| 10 | // ServeHTTP calls f(w, r) and handles error |
| 11 | func (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 | |
| 17 | func 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 | |
| iomodo | 493dd48 | 2021-04-02 00:07:51 +0400 | [diff] [blame] | 26 | w.WriteHeader(statusCode) |
| iomodo | a19d479 | 2021-03-26 00:27:25 +0400 | [diff] [blame] | 27 | |
| 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 | |
| iomodo | a19d479 | 2021-03-26 00:27:25 +0400 | [diff] [blame] | 36 | return nil |
| 37 | } |