-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.go
83 lines (76 loc) · 2.35 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
package gorest
import (
"encoding/json"
"github.com/dimonrus/porterr"
"io/ioutil"
"net/http"
)
// NewOkJsonResponse New Json Response without error
func NewOkJsonResponse(message interface{}, data interface{}, meta interface{}) *JsonResponse {
return &JsonResponse{HttpCode: http.StatusOK, Message: message, Data: data, Meta: meta}
}
// NewErrorJsonResponse New Json Response with error
func NewErrorJsonResponse(e porterr.IError) *JsonResponse {
httpCode := http.StatusInternalServerError
if e != nil && e.GetHTTP() >= http.StatusBadRequest && e.GetHTTP() <= http.StatusNetworkAuthenticationRequired {
httpCode = e.GetHTTP()
}
return &JsonResponse{HttpCode: httpCode, Error: e}
}
// Send response to client
func Send(writer http.ResponseWriter, response *JsonResponse) {
SendJson(writer, response.HttpCode, response)
}
// SendRawJson send raw JSON
func SendRawJson(writer http.ResponseWriter, httpCode int, data json.RawMessage) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(httpCode)
if data == nil {
return
}
writer.Write(data)
}
// SendJson Sent json into http writer
func SendJson(writer http.ResponseWriter, httpCode int, data interface{}) {
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(httpCode)
if data == nil {
return
}
body, err := json.Marshal(data)
if err != nil {
_, err := writer.Write([]byte("JSON marshal failed: " + err.Error()))
if err != nil {
panic(err)
}
return
}
_, err = writer.Write(body)
if err != nil {
panic(err)
}
}
// ResponseErrorStrategy Default response strategy
func ResponseErrorStrategy(response *http.Response) error {
var e porterr.IError
if response.StatusCode >= http.StatusBadRequest {
// Default error message
message := http.StatusText(response.StatusCode) + ": " + response.Request.URL.Path + " Service: " + response.Request.Host
// Init Error
e = porterr.New(porterr.PortErrorResponse, message).HTTP(response.StatusCode)
// Init response struct
result := &JsonResponse{Error: e}
// Read response body
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return e.PushDetail(porterr.PortErrorBody, "body", err.Error())
}
if len(body) != 0 {
err = json.Unmarshal(body, result)
if err != nil {
e = e.PushDetail(porterr.PortErrorBody, "body", err.Error())
}
}
}
return e
}