-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.go
40 lines (32 loc) · 1.16 KB
/
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
32
33
34
35
36
37
38
39
40
package httpbulb
import (
"encoding/json"
"fmt"
"net/http"
)
// RenderResponse is the default renderer function used by httpbulb.
// It renders JSON by default and it can be overridden on program's `init` function.
var RenderResponse func(http.ResponseWriter, int, interface{}) = renderJson
// RenderError renders the error message.
// It renders JSON by default and it can be overridden on program's `init` function.
var RenderError func(http.ResponseWriter, string, int) = JsonError
func renderJson(w http.ResponseWriter, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.Encode(data)
}
// TextError is a shortcut func for writing an error in `text/plain`
func TextError(w http.ResponseWriter, err string, code int) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(code)
fmt.Fprintln(w, err)
}
// JsonError is a shortcut func for writing an error in `application/json`
func JsonError(w http.ResponseWriter, err string, code int) {
if err == "" {
err = http.StatusText(code)
}
renderJson(w, code, &ErrorResponse{Error: err})
}