-
Notifications
You must be signed in to change notification settings - Fork 46
/
http_response.go
59 lines (51 loc) · 1.63 KB
/
http_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
package wrapper
import (
"encoding/json"
"encoding/xml"
"net/http"
"pkg.agungdp.dev/candi/candihelper"
"pkg.agungdp.dev/candi/candishared"
)
// HTTPResponse format
type HTTPResponse struct {
Success bool `json:"success"`
Code int `json:"code"`
Message string `json:"message"`
Meta interface{} `json:"meta,omitempty"`
Data interface{} `json:"data,omitempty"`
Errors interface{} `json:"errors,omitempty"`
}
// NewHTTPResponse for create common response
func NewHTTPResponse(code int, message string, params ...interface{}) *HTTPResponse {
commonResponse := new(HTTPResponse)
for _, param := range params {
switch val := param.(type) {
case *candishared.Meta, candishared.Meta:
commonResponse.Meta = val
case candihelper.MultiError:
commonResponse.Errors = val.ToMap()
case error:
commonResponse.Errors = candihelper.NewMultiError().Append("detail", val).ToMap()
default:
commonResponse.Data = param
}
}
if code < http.StatusBadRequest {
commonResponse.Success = true
}
commonResponse.Code = code
commonResponse.Message = message
return commonResponse
}
// JSON for set http JSON response (Content-Type: application/json) with parameter is http response writer
func (resp *HTTPResponse) JSON(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(resp.Code)
return json.NewEncoder(w).Encode(resp)
}
// XML for set http XML response (Content-Type: application/xml)
func (resp *HTTPResponse) XML(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(resp.Code)
return xml.NewEncoder(w).Encode(resp)
}