-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
71 lines (62 loc) · 1.67 KB
/
handler.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
package httputil
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
// HandlerFunc is a function that takes an HTTP request and returns a (data, err) tuple.
type HandlerFunc func(r *http.Request) (interface{}, error)
// Error returns an error object for the provided HTTP status code.
func Error(code int) error {
return httpError{code, fmt.Sprintf("HTTP %d", code)}
}
// ErrorMessage returns an error object for the provided HTTP status code.
func ErrorMessage(code int, message string) error {
return httpError{code, message}
}
// ErrorHandler will always return an error with the provided HTTP status code.
func ErrorHandler(code int) http.HandlerFunc {
return Handler(func(r *http.Request) (interface{}, error) {
return nil, Error(code)
})
}
// Handler turns a function that returns a (data, err) tuple into a http.HandlerFunc.
func Handler(f HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
v, err := f(r)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err != nil {
writeError(w, err)
return
}
b, err := json.Marshal(v)
if err != nil {
writeError(w, err)
return
}
_, err = w.Write(b)
if err != nil {
writeError(w, err)
}
}
}
type httpError struct {
code int
message string
}
func (e httpError) Error() string {
return e.message
}
func writeError(w http.ResponseWriter, err error) {
if httpErr, ok := err.(httpError); ok {
w.WriteHeader(httpErr.code)
} else {
log.Printf("Unknown non-HTTP error %v", err)
w.WriteHeader(500)
}
payload := map[string]string{"error": err.Error()}
data, _ := json.Marshal(payload)
w.Write(data)
}