-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_helper.go
48 lines (40 loc) · 1.17 KB
/
http_helper.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"
"io/ioutil"
"net/http"
)
func ReadPostBody(res http.ResponseWriter, req *http.Request) []byte {
// Read body
data, err := ioutil.ReadAll(req.Body)
if err != nil {
BadRequest(&res, err.Error())
return nil
}
return data
}
func WriteJSON(res http.ResponseWriter, element interface{}) {
jsonElement, err := json.Marshal(&element)
if err != nil {
HttpError(&res, "Error converting to JSON", 500, err.Error())
return
}
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(jsonElement)
}
func HttpError(res *http.ResponseWriter, errMsg string, errCode int, logMsg string) {
Error.Println(errMsg, logMsg)
http.Error(*res, errMsg, errCode)
}
func BadRequest(res *http.ResponseWriter, errMsg string) {
HttpError(res, errMsg, 400, "")
}
func EmptyResponse(res *http.ResponseWriter, errMsg string) {
HttpError(res, "", 204, errMsg)
}
func NotFound(res *http.ResponseWriter, errMsg string) {
HttpError(res, errMsg, 404, "")
}
func InternalServerError(res *http.ResponseWriter, errMsg string) {
HttpError(res, errMsg, 500, "")
}