-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapiutils.go
More file actions
97 lines (82 loc) · 2.18 KB
/
apiutils.go
File metadata and controls
97 lines (82 loc) · 2.18 KB
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
package apiutils
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
)
func RequireParams(form url.Values, params []string) error {
for _, param := range params {
if len(form[param]) == 0 {
return fmt.Errorf("Missing param: %s", param)
}
}
return nil
}
// ReadParams reads in parameters from the request, using the content type.
func ReadParams(r *http.Request) (map[string]interface{}, error) {
params := make(map[string]interface{})
if r.Header.Get("Content-Type") == "application/json" {
decoder := json.NewDecoder(r.Body)
return params, decoder.Decode(¶ms)
} else {
r.ParseForm()
// Take first argument, equivalent to Get()
for k, v := range r.Form {
params[k] = v[0]
}
return params, nil
}
}
func RequireFormParams(r *http.Request, params []string) error {
for _, param := range params {
if len(r.FormValue(param)) == 0 {
return fmt.Errorf("Missing param: %s", param)
}
}
return nil
}
type ErrorResponse struct {
Status int `json:"status"`
Message string `json:"message"`
StatusText string `json:"error"`
}
func (T ErrorResponse) Error() string {
return fmt.Sprintf("Error (%d): %s", T.Status, T.Message)
}
func NewErrorResponse(status int, message string) ErrorResponse {
statusText := http.StatusText(status)
if statusText == "" {
statusText = ExtentionStatusText(status)
}
return ErrorResponse{
Status: status,
Message: message,
StatusText: statusText,
}
}
func ServeJSON(w http.ResponseWriter, v interface{}) {
content, err := json.MarshalIndent(v, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
w.Header().Set("Content-Type", "application/json")
w.Write(content)
}
func ServeError(w http.ResponseWriter, errRes ErrorResponse) {
w.WriteHeader(errRes.Status)
ServeJSON(w, errRes)
}
const (
StatusUnprocessableEntity = 422
)
// extentionStatusText supports extra status codes that the stdlib http package does not.
var extentionStatusText = map[int]string{
StatusUnprocessableEntity: "Unprocessable entity",
}
func ExtentionStatusText(code int) string {
return extentionStatusText[code]
}