/
http.go
50 lines (39 loc) · 941 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
42
43
44
45
46
47
48
49
50
package coreapi
import (
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
func wrapAPIHandler(logger Logger) func(fun APIHandler) http.Handler {
return func(handler APIHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ok bool
w.Header().Set("Content-Type", "application/json")
seccess, err := handler(r)
if err != nil {
var apiErr APIError
innerErr := errors.Cause(err)
if apiErr, ok = innerErr.(APIError); !ok {
logger.Err("API wrapper: %+v", err)
apiErr = InternalServerErr
}
w.WriteHeader(apiErr.StatusCode)
if apiErr == EntityNotFoundErr {
return
}
b, _ := json.Marshal(apiErr)
w.Write(b)
return
}
w.WriteHeader(http.StatusOK)
if seccess == nil {
return
}
var body []byte
if body, ok = seccess.([]byte); !ok {
body, _ = json.Marshal(seccess)
}
w.Write(body)
})
}
}