forked from go-chi/chi
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresponse.go
More file actions
100 lines (81 loc) · 1.87 KB
/
response.go
File metadata and controls
100 lines (81 loc) · 1.87 KB
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
97
98
99
100
package phi
import (
"encoding/json"
"net/http"
)
type Response struct {
http.ResponseWriter
}
// send response with application/json
//
// content will be wrapped in { "data" : <content> } object
func (w Response) JSON(data interface{}) *Error {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
parsed, err := json.Marshal(Map{
"data": data,
})
if err != nil {
return &parseError
}
if _, er := w.Write(parsed); er != nil {
return &writingError
}
return nil
}
// send response with contentType
func (w Response) Response(data []byte, contentType string) *Error {
w.Header().Set("Content-Type", contentType)
if _, err := w.Write(data); err != nil {
return &writingError
}
return nil
}
// send error response with status code
//
// default error will look like this:
//
// {
// "error": "unknownError",
// "message": err.Error()
// }
func (w Response) Error(err error) *Error {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
parsed, er := json.Marshal(Map{
"error": "unknownError",
"message": err.Error(),
})
if er != nil {
return &parseError
}
if _, er = w.Write(parsed); er != nil {
return &writingError
}
return nil
}
// send error response with custom status code
func (w Response) ErrorCustomStatus(err error, statusCode int) *Error {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
parsed, er := json.Marshal(Map{
"error": "unknownError",
"message": err.Error(),
})
if er != nil {
return &parseError
}
w.WriteHeader(statusCode)
if _, er = w.Write(parsed); er != nil {
return &writingError
}
return nil
}
// send redirect response
func (w Response) Redirect(req *http.Request, location string, code int) *Error {
http.Redirect(w.ResponseWriter, req, location, code)
return nil
}