-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
56 lines (46 loc) · 1.39 KB
/
io.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package httpjson
import (
"encoding/json"
"net/http"
"github.com/diamcircle/go/support/errors"
)
type contentType int
const (
JSON contentType = iota
HALJSON
HEALTHJSON
)
// renderToString renders the provided data as a json string
func renderToString(data interface{}, pretty bool) ([]byte, error) {
if pretty {
return json.MarshalIndent(data, "", " ")
}
return json.Marshal(data)
}
// Render write data to w, after marshalling to json. The response header is
// set based on cType.
func Render(w http.ResponseWriter, data interface{}, cType contentType) {
RenderStatus(w, http.StatusOK, data, cType)
}
// RenderStatus write data to w, after marshalling to json.
// The response header is set based on cType.
// The response status code is set to the statusCode.
func RenderStatus(w http.ResponseWriter, statusCode int, data interface{}, cType contentType) {
js, err := renderToString(data, true)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Disposition", "inline")
switch cType {
case HALJSON:
w.Header().Set("Content-Type", "application/hal+json; charset=utf-8")
case HEALTHJSON:
w.Header().Set("Content-Type", "application/health+json; charset=utf-8")
default:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
}
w.WriteHeader(statusCode)
w.Write(js)
}
var ErrBadRequest = errors.New("bad request")