forked from sebastienfr/handsongo
/
utils.go
72 lines (61 loc) · 2.23 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
package web
import (
"encoding/json"
"github.com/gorilla/mux"
logger "github.com/sirupsen/logrus"
"net/http"
)
const (
// ResponseHeaderContentTypeKey is the key used for response content type
ResponseHeaderContentTypeKey = "Content-Type"
// ResponseHeaderContentTypeJSONUTF8 is the key used for UTF8 JSON response
ResponseHeaderContentTypeJSONUTF8 = "application/json; charset=UTF-8"
resourceNotFound = "Resource not found"
errorMsg = "Error"
)
// SendJSONWithHTTPCode outputs JSON with an HTTP code
func SendJSONWithHTTPCode(w http.ResponseWriter, d interface{}, code int) {
w.Header().Set(ResponseHeaderContentTypeKey, ResponseHeaderContentTypeJSONUTF8)
w.WriteHeader(code)
if d != nil {
err := json.NewEncoder(w).Encode(d)
if err != nil {
logger.WithField("body", d).WithField("code", code).Error("error while encoding JSON body of response")
// panic will cause the http.StatusInternalServerError to be send to users
panic(err)
}
}
}
// SendJSONOk outputs a JSON with http.StatusOK code
func SendJSONOk(w http.ResponseWriter, d interface{}) {
SendJSONWithHTTPCode(w, d, http.StatusOK)
}
// SendJSONError sends error with a custom message and error code
func SendJSONError(w http.ResponseWriter, error string, code int) {
SendJSONWithHTTPCode(w, map[string]string{errorMsg: error}, code)
}
// SendJSONNotFound produces a http.StatusNotFound response with the following JSON, '{"Error":"Resource not found"}'
func SendJSONNotFound(w http.ResponseWriter) {
SendJSONError(w, resourceNotFound, http.StatusNotFound)
}
// NotFoundHandler return a JSON implementation of the not found handler
func NotFoundHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
SendJSONNotFound(w)
}
}
// ParamAsString returns an URL parameter /{name} as a string
func ParamAsString(name string, r *http.Request) string {
vars := mux.Vars(r)
value := vars[name]
return value
}
// QueryParamAsString Param Return a url param as an int
func QueryParamAsString(name string, r *http.Request) string {
return r.URL.Query().Get(name)
}
// GetJSONContent returns the JSON content of a request
func GetJSONContent(v interface{}, r *http.Request) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(v)
}