-
Notifications
You must be signed in to change notification settings - Fork 12
/
transport.go
102 lines (85 loc) · 2.41 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
package main
import (
"context"
"encoding/json"
"net/http"
"github.com/go-kit/kit/endpoint"
)
func makeUppercaseEndpoint(svc StringService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(uppercaseRequest)
v, err := svc.Uppercase(ctx, req.S)
if err != nil {
return uppercaseResponse{v, err.Error()}, nil
}
return uppercaseResponse{v, ""}, nil
}
}
func makeCountEndpoint(svc StringService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(countRequest)
v := svc.Count(ctx, req.S)
return countResponse{v}, nil
}
}
func makeAuthEndpoint(svc AuthService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(authRequest)
token, err := svc.Auth(req.ClientID, req.ClientSecret)
if err != nil {
return nil, err
}
return authResponse{token, ""}, nil
}
}
func decodeAuthRequest(_ context.Context, r *http.Request) (interface{}, error) {
var request authRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, err
}
return request, nil
}
func decodeUppercaseRequest(_ context.Context, r *http.Request) (interface{}, error) {
var request uppercaseRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, err
}
return request, nil
}
func decodeCountRequest(_ context.Context, r *http.Request) (interface{}, error) {
var request countRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, err
}
return request, nil
}
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
return json.NewEncoder(w).Encode(response)
}
type uppercaseRequest struct {
S string `json:"s"`
}
type uppercaseResponse struct {
V string `json:"v"`
Err string `json:"err,omitempty"`
}
type countRequest struct {
S string `json:"s"`
}
type countResponse struct {
V int `json:"v"`
}
type authRequest struct {
ClientID string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
}
type authResponse struct {
Token string `json:"token,omitempty"`
Err string `json:"err,omitempty"`
}
func authErrorEncoder(_ context.Context, err error, w http.ResponseWriter) {
code := http.StatusUnauthorized
msg := err.Error()
w.WriteHeader(code)
json.NewEncoder(w).Encode(authResponse{Token: "", Err: msg})
}