forked from facesea/banshee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
41 lines (35 loc) · 988 Bytes
/
util.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
// Copyright 2015 Eleme Inc. All rights reserved.
package webapp
import (
"encoding/json"
"io"
"net/http"
"strconv"
)
// ResponseJSONOK writes ok response.
func ResponseJSONOK(w http.ResponseWriter, v interface{}) error {
return ResponseJSON(w, http.StatusOK, v)
}
// ResponseJSON encodes value to json and write as response.
func ResponseJSON(w http.ResponseWriter, code int, v interface{}) error {
// Encode JSON.
b, err := json.Marshal(v)
if err != nil {
return err
}
// Write response.
s := string(b)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(s)))
w.WriteHeader(code)
io.WriteString(w, s)
return nil
}
// ResponseError writes WebError as response.
func ResponseError(w http.ResponseWriter, err *WebError) error {
return ResponseJSON(w, err.Code, err)
}
// RequestBind binds request data into value.
func RequestBind(r *http.Request, v interface{}) error {
return json.NewDecoder(r.Body).Decode(v)
}