-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhttp.go
41 lines (32 loc) · 886 Bytes
/
http.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
package storm
import (
"encoding/json"
"net/http"
)
// HandlerFunc is an adaptor for the http.HandlerFunc that returns JSON data.
type HandlerFunc func(r *http.Request) (interface{}, error)
// Send sends JSON data to the client using the supplied HTTP status code.
func Send(rw http.ResponseWriter, code int, data interface{}) {
enc := json.NewEncoder(rw)
enc.SetIndent("", " ")
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(code)
_ = enc.Encode(data)
}
// NoContent sends a 204 No Content response
func NoContent(rw http.ResponseWriter) {
rw.WriteHeader(http.StatusNoContent)
}
func Handle(rw http.ResponseWriter, r *http.Request, handler HandlerFunc) error {
response, err := handler(r)
if err != nil {
SendError(rw, err)
return err
}
if response == nil {
NoContent(rw)
return nil
}
Send(rw, http.StatusOK, response)
return nil
}