-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
44 lines (36 loc) · 820 Bytes
/
util.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
package handle
import (
"encoding/json"
"net/http"
)
type resError struct {
Type string
Message string
}
func badRequest(w http.ResponseWriter, err error) {
send(w, http.StatusBadRequest, resError{
Type: "BadRequest",
Message: err.Error(),
})
}
var unauthorizedError = resError{
Type: "Unauthorized",
Message: "You must be authenticated to make API requests.",
}
func unauthorized(w http.ResponseWriter) {
send(w, http.StatusUnauthorized, unauthorizedError)
}
func ok(w http.ResponseWriter, v interface{}) {
send(w, http.StatusOK, v)
}
func send(w http.ResponseWriter, status int, v interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
encoder := json.NewEncoder(w)
must(encoder.Encode(v))
}
func must(err error) {
if err != nil {
panic(err)
}
}