/
http.go
138 lines (108 loc) · 3.91 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
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
package transport
import (
"context"
"encoding/json"
"errors"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/tracing/zipkin"
"github.com/go-kit/kit/transport"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/gorilla/mux"
"github.com/longjoy/micro-go-book/ch13-seckill/oauth-service/endpoint"
"github.com/longjoy/micro-go-book/ch13-seckill/oauth-service/service"
gozipkin "github.com/openzipkin/zipkin-go"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
var (
ErrorBadRequest = errors.New("invalid request parameter")
ErrorGrantTypeRequest = errors.New("invalid request grant type")
ErrorTokenRequest = errors.New("invalid request token")
ErrInvalidClientRequest = errors.New("invalid client message")
)
// MakeHttpHandler make http handler use mux
func MakeHttpHandler(ctx context.Context, endpoints endpoint.OAuth2Endpoints, tokenService service.TokenService, clientService service.ClientDetailsService,zipkinTracer *gozipkin.Tracer, logger log.Logger) http.Handler {
r := mux.NewRouter()
zipkinServer := zipkin.HTTPServerTrace(zipkinTracer, zipkin.Name("http-transport"))
options := []kithttp.ServerOption{
kithttp.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
kithttp.ServerErrorEncoder(encodeError),
zipkinServer,
}
r.Path("/metrics").Handler(promhttp.Handler())
clientAuthorizationOptions := []kithttp.ServerOption{
kithttp.ServerBefore(makeClientAuthorizationContext(clientService, logger)),
kithttp.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
kithttp.ServerErrorEncoder(encodeError),
zipkinServer,
}
r.Methods("POST").Path("/oauth/token").Handler(kithttp.NewServer(
endpoints.TokenEndpoint,
decodeTokenRequest,
encodeJsonResponse,
clientAuthorizationOptions...,
))
r.Methods("POST").Path("/oauth/check_token").Handler(kithttp.NewServer(
endpoints.CheckTokenEndpoint,
decodeCheckTokenRequest,
encodeJsonResponse,
clientAuthorizationOptions...,
))
// create health check handler
r.Methods("GET").Path("/health").Handler(kithttp.NewServer(
endpoints.HealthCheckEndpoint,
decodeHealthCheckRequest,
encodeJsonResponse,
options...,
))
return r
}
func makeClientAuthorizationContext(clientDetailsService service.ClientDetailsService, logger log.Logger) kithttp.RequestFunc {
return func(ctx context.Context, r *http.Request) context.Context {
if clientId, clientSecret, ok := r.BasicAuth(); ok {
clientDetails, err := clientDetailsService.GetClientDetailByClientId(ctx, clientId, clientSecret)
if err == nil {
return context.WithValue(ctx, endpoint.OAuth2ClientDetailsKey, clientDetails)
}
}
return context.WithValue(ctx, endpoint.OAuth2ErrorKey, ErrInvalidClientRequest)
}
}
func decodeTokenRequest(ctx context.Context, r *http.Request) (interface{}, error) {
grantType := r.URL.Query().Get("grant_type")
if grantType == ""{
return nil, ErrorGrantTypeRequest
}
return &endpoint.TokenRequest{
GrantType:grantType,
Reader:r,
}, nil
}
func decodeCheckTokenRequest(ctx context.Context, r *http.Request) (interface{}, error) {
tokenValue := r.URL.Query().Get("token")
if tokenValue == ""{
return nil, ErrorTokenRequest
}
return &endpoint.CheckTokenRequest{
Token:tokenValue,
}, nil
}
// encode errors from business-logic
func encodeError(_ context.Context, err error, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
switch err {
default:
w.WriteHeader(http.StatusInternalServerError)
}
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
}
func encodeJsonResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
w.Header().Set("Content-Type", "application/json;charset=utf-8")
return json.NewEncoder(w).Encode(response)
}
// decodeHealthCheckRequest decode request
func decodeHealthCheckRequest(ctx context.Context, r *http.Request) (interface{}, error) {
return endpoint.HealthRequest{}, nil
}