-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
277 lines (248 loc) · 7.65 KB
/
transport.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package slcansvc
import (
"bytes"
"context"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
"github.com/go-kit/kit/transport"
httptransport "github.com/go-kit/kit/transport/http"
"github.com/go-kit/log"
"github.com/gorilla/mux"
httpSwagger "github.com/swaggo/http-swagger/v2"
)
var (
// ErrTransportBadRouting is returned when an expected path variable is missing.
// It always indicates programmer error.
ErrTransportBadRouting = errors.New("Transport: bad routing")
)
func MakeHTTPHandler(s IService, logger log.Logger) http.Handler {
r := mux.NewRouter()
e := MakeServerEndpoints(s)
options := []httptransport.ServerOption{
httptransport.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
httptransport.ServerErrorEncoder(encodeError),
}
r.Methods("GET").Path("/slcan/{id}").Handler(httptransport.NewServer(
e.GetMessageEndpoint,
DecodeGetMessageRequest,
EncodeResponse,
options...,
))
r.Methods("POST").Path("/slcan").Handler(httptransport.NewServer(
e.PostMessageEndpoint,
DecodePostMessageRequest,
EncodeResponse,
options...,
))
r.Methods("PUT").Path("/slcan/{id}").Handler(httptransport.NewServer(
e.PutMessageEndpoint,
DecodePutMessageRequest,
EncodeResponse,
options...,
))
r.Methods("DELETE").Path("/slcan/{id}").Handler(httptransport.NewServer(
e.DeleteMessageEndpoint,
DecodeDeleteMessageRequest,
EncodeResponse,
options...,
))
r.Methods("POST").Path("/slcan/reboot").Handler(httptransport.NewServer(
e.RebootEndpoint,
DecodeRebootRequest,
EncodeResponse,
options...,
))
r.Methods("POST").Path("/slcan/unlock").Handler(httptransport.NewServer(
e.UnlockEndpoint,
DecodeUnlockRequest,
EncodeResponse,
options...,
))
r.PathPrefix("/slcan/docs").Handler(httpSwagger.WrapHandler)
return r
}
func DecodeGetMessageRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
return nil, ErrTransportBadRouting
}
i, err := strconv.Atoi(id)
if err != nil {
return nil, ErrTransportBadRouting
}
return getMessageRequest{ID: i}, nil
}
func DecodePostMessageRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
var req postMessageRequest
if e := json.NewDecoder(r.Body).Decode(&req.Msg); e != nil {
return nil, e
}
return req, nil
}
func DecodePutMessageRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
return nil, ErrTransportBadRouting
}
var msg Message
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
return nil, err
}
i, err := strconv.Atoi(id)
if err != nil {
return nil, ErrTransportBadRouting
}
return putMessageRequest{ID: i, Msg: msg}, nil
}
func DecodeDeleteMessageRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
return nil, ErrTransportBadRouting
}
i, err := strconv.Atoi(id)
if err != nil {
return nil, ErrTransportBadRouting
}
return deleteMessageRequest{ID: i}, nil
}
func DecodeRebootRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
return rebootRequest{}, nil
}
func DecodeUnlockRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
return unlockRequest{}, nil
}
func EncodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
if e, ok := response.(errorer); ok && e.error() != nil {
// Not a Go kit transport error, but a business-logic error.
// Provide those as HTTP errors.
encodeError(ctx, e.error(), w)
return nil
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return json.NewEncoder(w).Encode(response)
}
func EncodeGetMessageRequest(ctx context.Context, req *http.Request, request interface{}) error {
// r.Methods("GET").Path("/slcan/{id}")
r := request.(getMessageRequest)
id := strconv.Itoa(r.ID)
req.URL.Path = "/slcan/" + id
return encodeRequest(ctx, req, nil)
}
func EncodePostMessageRequest(ctx context.Context, req *http.Request, request interface{}) error {
// r.Methods("POST").Path("/slcan")
req.URL.Path = "/slcan"
return encodeRequest(ctx, req, request)
}
func EncodePutMessageRequest(ctx context.Context, req *http.Request, request interface{}) error {
// r.Methods("PUT").Path("/slcan/{id}")
r := request.(putMessageRequest)
id := strconv.Itoa(r.ID)
req.URL.Path = "/slcan/" + id
return encodeRequest(ctx, req, request)
}
func EncodeDeleteMessageRequest(ctx context.Context, req *http.Request, request interface{}) error {
// r.Methods("DELETE").Path("/slcan/{id}")
r := request.(deleteMessageRequest)
id := strconv.Itoa(r.ID)
req.URL.Path = "/slcan/" + id
return encodeRequest(ctx, req, request)
}
func EncodeRebootRequest(ctx context.Context, req *http.Request, request interface{}) error {
// r.Methods("POST").Path("/slcan/reboot")
req.URL.Path = "/slcan/reboot"
return encodeRequest(ctx, req, request)
}
func EncodeUnlockRequest(ctx context.Context, req *http.Request, request interface{}) error {
// r.Methods("POST").Path("/slcan/unlock")
req.URL.Path = "/slcan/unlock"
return encodeRequest(ctx, req, request)
}
func DecodeGetMessageResponse(_ context.Context, r *http.Response) (interface{}, error) {
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
var resp getMessageResponse
err := json.NewDecoder(r.Body).Decode(&resp)
return resp, err
}
func DecodePostMessageResponse(_ context.Context, r *http.Response) (interface{}, error) {
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
var resp postMessageResponse
err := json.NewDecoder(r.Body).Decode(&resp)
return resp, err
}
func DecodePutMessageResponse(_ context.Context, r *http.Response) (interface{}, error) {
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
var resp putMessageResponse
err := json.NewDecoder(r.Body).Decode(&resp)
return resp, err
}
func DecodeDeleteMessageResponse(_ context.Context, r *http.Response) (interface{}, error) {
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
var resp deleteMessageResponse
err := json.NewDecoder(r.Body).Decode(&resp)
return resp, err
}
func DecodeRebootResponse(_ context.Context, r *http.Response) (interface{}, error) {
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
var resp rebootResponse
err := json.NewDecoder(r.Body).Decode(&resp)
return resp, err
}
func DecodeUnlockResponse(_ context.Context, r *http.Response) (interface{}, error) {
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
var resp unlockResponse
err := json.NewDecoder(r.Body).Decode(&resp)
return resp, err
}
type errorer interface {
error() error
}
// encodeRequest likewise JSON-encodes the request to the HTTP request body.
// Don't use it directly as a transport/http.Client EncodeRequestFunc:
// Endpoints require mutating the HTTP method and request path.
func encodeRequest(_ context.Context, req *http.Request, request interface{}) error {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(request)
if err != nil {
return err
}
req.Body = ioutil.NopCloser(&buf)
return nil
}
func encodeError(_ context.Context, err error, w http.ResponseWriter) {
if err == nil {
panic("encodeError with nil error")
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(codeFrom(err))
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
}
func codeFrom(err error) int {
switch err {
case ErrDatabaseNotFound:
return http.StatusNotFound
case ErrDatabaseAlreadyExists, ErrTransportBadRouting:
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}