/
utils.go
223 lines (196 loc) · 5.21 KB
/
utils.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"regexp"
"strings"
"time"
)
func ParseBody(r *http.Request, x interface{}) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
// exception handling code here
return err
}
defer r.Body.Close()
// ok. parse json to struct.
err = json.Unmarshal([]byte(body), x)
if err != nil {
// exception handling code here
return err
}
// ok.
return nil
}
func ParseResponseBody(r *http.Response, x interface{}) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
// exception handling code here
return err
}
defer r.Body.Close()
// ok. parse json to struct.
err = json.Unmarshal([]byte(body), x)
if err != nil {
// exception handling code here
return err
}
// ok.
return nil
}
// GetRandomNumber returns a random number.
func GetRandomNumber() int {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(99999999) + 1
return n
}
// GenerateID returns a randomly generated ID string.
// The randomly generated ID string is in the following format:
// YYYY.MM.DD.RRRRRRRR
// where
// - YYYY represents the Year of the system date
// - MM represents the Month of the system date
// - DD represents the Day of the system date
// - RRRRRRRR is the zero-padded random number
func GenerateID() string {
year, month, day := time.Now().Local().Date()
randomNumber := GetRandomNumber()
ID := fmt.Sprintf("%d%02d%02d.%09d", year, int(month), day, randomNumber)
return ID
}
// IsValidEmailFormat checks if the input, v is in a valid email format.
// Return true if valid; false if not valid.
func IsValidEmailFormat(v string) bool {
pattern := regexp.MustCompile(`^[a-z0-9_]+[.-][a-z0-9]+@\w+\.([a-z0-9]{2,4}|[a-z]{2}.[a-z]{2})$`)
return pattern.MatchString(v)
}
// IsAlphaAndSpaceOnly checks if the input, v contains only alphabets and white space characters (i.e. space or tab) only.
// Return true if valid; false if not valid.
func IsAlphaAndSpaceOnly(v string) bool {
pattern := regexp.MustCompile(`^[a-zA-z\s]+$`)
return pattern.MatchString(v)
}
// AreAllowedCharacters checks if the input, v contains any of the following characters that are not allowed:
// - /
// - \
// - -
// Returns
// - true if v does not contain any not allowed characters;
// - false if v contains any of the not allowed characters.
func AreAllowedCharacters(v string) bool {
pattern := regexp.MustCompile(`^([a-zA-z0-9]|[^\/-])+$`)
return pattern.MatchString(v)
}
// SendErrorMsgToClient prepares:
// - a INTERNAL SERVER ERROR response header;
// - a JSON body containing:
// * "ok" attribute, set to false;
// * "msg" attribute set to the error message passed in;
// * "data" attribute set to {}
func SendErrorMsgToClient(w *http.ResponseWriter, err error) {
(*w).WriteHeader(http.StatusInternalServerError)
body := fmt.Sprintf(`{
"ok" : false,
"msg" : "%s",
"data" : {}
}`, err.Error())
(*w).Write([]byte(body))
//
}
func SendConflictMsgToClient(w *http.ResponseWriter, err error) {
(*w).WriteHeader(http.StatusConflict)
body := fmt.Sprintf(`{
"ok" : false,
"msg" : "%s",
"data" : {}
}`, err.Error())
(*w).Write([]byte(body))
//
}
// SendNotFoundMsgToClient prepares:
// - a NOT FOUND response header;
// - a JSON body containing:
// * "ok" attribute, set to false;
// * "msg" attribute set to the error message passed in;
// * "data" attribute set to {}
func SendNotFoundMsgToClient(w *http.ResponseWriter, err error) {
(*w).WriteHeader(http.StatusNotFound)
body := fmt.Sprintf(`{
"ok" : false,
"msg" : "%s",
"data" : {}
}`, err.Error())
(*w).Write([]byte(body))
//
}
// SendBadRequestMsgToClient prepares:
// - a BAD REQUEST response header;
// - a JSON body containing:
// * "ok" attribute, set to false;
// * "msg" attribute set to the error message passed in;
// * "data" attribute set to {}
func SendBadRequestMsgToClient(w *http.ResponseWriter, err error) {
(*w).WriteHeader(http.StatusBadRequest)
body := fmt.Sprintf(`{
"ok" : false,
"msg" : "%s",
"data" : {}
}`, err.Error())
(*w).Write([]byte(body))
//
}
// SendForbiddenMsgToClient prepares:
// - a FORBIDDEN response header;
// - a JSON body containing:
// * "ok" attribute, set to false;
// * "msg" attribute set to the error message passed in;
// * "data" attribute set to {}
func SendForbiddenMsgToClient(w *http.ResponseWriter, err error) {
(*w).WriteHeader(http.StatusForbidden)
body := fmt.Sprintf(`{
"ok" : false,
"msg" : "%s",
"data" : {}
}`, err.Error())
(*w).Write([]byte(body))
//
}
// SendDataToClient prepares:
// - a OK header;
// - a JSON body containing:
// * "ok" attribute, set to true;
// * "msg" attriubte;
// * "data" attribute, set to the data passed in
// and send the response to the client.
func SendDataToClient(w *http.ResponseWriter, data []byte, msg string) {
(*w).WriteHeader(http.StatusOK)
var _msg string
if strings.TrimSpace(msg) == "" {
_msg = "n.a."
} else {
_msg = msg
}
if data != nil {
// data is available
body := fmt.Sprintf(`{
"ok" : true,
"msg" : "%s",
"data" : %s
}`, _msg, string(data))
(*w).Write([]byte(body))
//
} else {
// no data
body := fmt.Sprintf(`{
"ok" : true,
"msg" : "%s",
"data" : {}
}`, _msg)
(*w).Write([]byte(body))
//
}
//
}