-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault.go
59 lines (46 loc) · 1.19 KB
/
default.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
package brouter
import (
"encoding/json"
"errors"
"net/http"
)
type defaultResponse struct {
Header defaultResponseHeader `json:"header"`
Data interface{} `json:"data"`
}
type defaultResponseHeader struct {
IsSuccess bool `json:"is_success"`
Reason string `json:"reason,omitempty"`
}
func defaultHandlerFunc(w http.ResponseWriter, r *http.Request) (interface{}, error) {
return nil, errors.New("nil handler")
}
func defaultHandlerErrorFunc(w http.ResponseWriter, r *http.Request, err error) {
var errorMessage string
if err != nil {
errorMessage = err.Error()
}
resp := &defaultResponse{
Header: defaultResponseHeader{
IsSuccess: false,
Reason: errorMessage,
},
Data: nil,
}
payload, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write(payload)
}
func defaultHandlerSuccessFunc(w http.ResponseWriter, r *http.Request, data interface{}) {
resp := &defaultResponse{
Header: defaultResponseHeader{
IsSuccess: true,
},
Data: data,
}
payload, _ := json.Marshal(resp)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(payload)
}