-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.go
96 lines (85 loc) · 2.4 KB
/
response.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package impart
import (
"encoding/json"
"net/http"
"strconv"
)
type (
// Envelope contains metadata and optional data for a response object.
// Responses will always contain a status code and either:
// - response Data on a 2xx response, or
// - an ErrorMessage on non-2xx responses
//
// ErrorType is not currently used.
Envelope struct {
Code int `json:"code"`
ErrorType string `json:"error_type,omitempty"`
ErrorMessage string `json:"error_msg,omitempty"`
Data interface{} `json:"data,omitempty"`
}
PlainErrEnvelope struct {
Error string `json:"error"`
}
)
func writeBody(w http.ResponseWriter, body []byte, status int, contentType string) error {
w.Header().Set("Content-Type", contentType+"; charset=UTF-8")
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(status)
_, err := w.Write(body)
return err
}
func RenderActivityJSON(w http.ResponseWriter, value interface{}, status int) error {
body, err := json.Marshal(value)
if err != nil {
return err
}
return writeBody(w, body, status, "application/activity+json")
}
func renderJSON(w http.ResponseWriter, value interface{}, status int) error {
body, err := json.Marshal(value)
if err != nil {
return err
}
return writeBody(w, body, status, "application/json")
}
func renderString(w http.ResponseWriter, status int, msg string) error {
return writeBody(w, []byte(msg), status, "text/plain")
}
// WriteSuccess writes the successful data and metadata to the ResponseWriter as
// JSON.
func WriteSuccess(w http.ResponseWriter, data interface{}, status int) error {
env := &Envelope{
Code: status,
Data: data,
}
return renderJSON(w, env, status)
}
// WriteError writes the error to the ResponseWriter as JSON.
func WriteError(w http.ResponseWriter, e HTTPError) error {
status := e.Status
if status == 0 {
status = 500
}
env := &Envelope{
Code: status,
ErrorMessage: e.Message,
}
return renderJSON(w, env, status)
}
// WriteOAuthError writes the error to the ResponseWriter as JSON.
func WriteOAuthError(w http.ResponseWriter, e HTTPError) error {
status := e.Status
if status == 0 {
status = 500
}
env := &PlainErrEnvelope{
Error: e.Message,
}
return renderJSON(w, env, status)
}
// WriteRedirect sends a redirect
func WriteRedirect(w http.ResponseWriter, e HTTPError) int {
w.Header().Set("Location", e.Message)
w.WriteHeader(e.Status)
return e.Status
}