This repository has been archived by the owner on Jul 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
json.go
74 lines (65 loc) · 1.64 KB
/
json.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package gosaas
import (
"encoding/json"
"io"
"log"
"net/http"
)
// Respond return an strruct with specific status as JSON.
//
// If data is an error it will be wrapped in a generic JSON object:
//
// {
// "status": 401,
// "error": "the result of data.Error()"
// }
//
// Example usage:
//
// func handler(w http.ResponseWriter, r *http.Request) {
// task := Task{ID: 123, Name: "My Task", Done: false}
// gosaas.Respond(w, r, http.StatusOK, task)
// }
func Respond(w http.ResponseWriter, r *http.Request, status int, data interface{}) error {
// change error into a real JSON serializable object
if e, ok := data.(error); ok {
var tmp = new(struct {
Status string `json:"status"`
Error string `json:"error"`
})
tmp.Status = "error"
tmp.Error = e.Error()
data = tmp
log.Println("error: ", e.Error())
}
js, err := json.Marshal(data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return err
}
// write the request ID
reqID, ok := r.Context().Value(ContextRequestID).(string)
if ok {
w.Header().Set("X-Request-ID", reqID)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(js)
logRequest(r, status)
return nil
}
// ParseBody parses the request JSON body into a struct.ParseBody
//
// Example usage:
//
// func handler(w http.ResponseWriter, r *http.Request) {
// var task Task
// if err := gosaas.ParseBody(r.Body, &task); err != nil {
// gosaas.Respond(w, r, http.StatusBadRequest, err)
// return
// }
// }
func ParseBody(body io.ReadCloser, result interface{}) error {
decoder := json.NewDecoder(body)
return decoder.Decode(result)
}