-
Notifications
You must be signed in to change notification settings - Fork 5
/
http.go
70 lines (55 loc) · 1.41 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package apiping
import (
"context"
"encoding/json"
"net/http"
"github.com/arquivei/foundationkit/errors"
"github.com/go-kit/kit/endpoint"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/gorilla/mux"
)
// MakeHTTPHandler returns a new http handler for endpoint
func MakeHTTPHandler(e endpoint.Endpoint) http.Handler {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(encodeError),
}
httpHandler := kithttp.NewServer(
e,
decodeRequest,
encodeResponse,
opts...,
)
r := mux.NewRouter()
r.Handle("/ping/v1", httpHandler).Methods("POST")
return r
}
func decodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
var body Request
defer r.Body.Close()
json.NewDecoder(r.Body).Decode(&body)
return body, nil
}
func encodeResponse(
ctx context.Context,
w http.ResponseWriter,
r interface{},
) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return json.NewEncoder(w).Encode(r)
}
func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
r := ResponseError{
Error: err.Error(),
}
w.WriteHeader(getHTTPStatus(err))
json.NewEncoder(w).Encode(r)
}
func getHTTPStatus(err error) (s int) {
switch errors.GetSeverity(err) {
case errors.SeverityInput:
return http.StatusBadRequest
}
// If we don't know what happened...
return http.StatusInternalServerError
}