-
Notifications
You must be signed in to change notification settings - Fork 0
/
responses.go
52 lines (46 loc) · 1.1 KB
/
responses.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
package main
import (
"encoding/json"
"net/http"
)
// Message response message
type Message struct {
Success bool `json:"success"`
Message string `json:"message"`
Payload interface{} `json:"payload"`
}
// ToBytes convert Message struct to byte array
func (s Message) ToBytes() ([]byte, error) {
j, e := json.Marshal(s)
return j, e
}
// Send convert message to byte array and send the response
func (s Message) Send(w http.ResponseWriter) {
resBody, err := s.ToBytes()
if err != nil {
ErrorResponse(http.StatusBadRequest, "Failed to send!", w)
} else {
Response(http.StatusOK, resBody, w)
}
}
// ErrorResponse send error message and code
func ErrorResponse(errCode int, errMessage string, w http.ResponseWriter) {
body, _ := Message{
Success: false,
Message: errMessage,
Payload: struct{}{},
}.ToBytes()
w.WriteHeader(errCode)
_, err := w.Write(body)
if err != nil {
panic(err)
}
}
// Response set the body and status code
func Response(statusCode int, body []byte, w http.ResponseWriter) {
w.WriteHeader(statusCode)
_, err := w.Write(body)
if err != nil {
panic(err)
}
}