-
Notifications
You must be signed in to change notification settings - Fork 1
/
responseHandlers.go
48 lines (37 loc) · 1.05 KB
/
responseHandlers.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
package main
import (
"encoding/json"
"net/http"
)
type BasicApiResponse struct {
Data interface{} `json:"data"`
Status int `json:"status"`
Total int `json:"total"`
Message string `json:"message"`
}
func respondWithJSON(w http.ResponseWriter, code int, payload map[string]interface{}) {
var apiResponse BasicApiResponse
apiResponse.Data = payload["data"]
if !isNil(apiResponse.Data) {
apiResponse.Status = 1
}
if !isNil(payload["status"]) {
apiResponse.Status = payload["status"].(int)
}
if !isNil(payload["total"]) {
apiResponse.Total = payload["total"].(int)
}
if !isNil(payload["message"].(string)) {
apiResponse.Message = payload["message"].(string)
}
if isNil(apiResponse.Total) {
apiResponse.Total = apiResponse.Status
}
response, _ := json.Marshal(apiResponse)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]interface{}{"message": message})
}