Package list golang-github-go-kit-kit / 5b4da74
remove server wide context from HTTP Transport in favor of per request context provided by net/http Bas van Beek 4 years ago
16 changed file(s) with 24 addition(s) and 78 deletion(s). Raw diff Collapse all Expand all
206206 // HTTP transport.
207207 go func() {
208208 logger := log.NewContext(logger).With("transport", "HTTP")
209 h := addsvc.MakeHTTPHandler(ctx, endpoints, tracer, logger)
209 h := addsvc.MakeHTTPHandler(endpoints, tracer, logger)
210210 logger.Log("addr", *httpAddr)
211211 errc <- http.ListenAndServe(*httpAddr, h)
212212 }()
1919
2020 // MakeHTTPHandler returns a handler that makes a set of endpoints available
2121 // on predefined paths.
22 func MakeHTTPHandler(ctx context.Context, endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger) http.Handler {
22 func MakeHTTPHandler(endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger) http.Handler {
2323 options := []httptransport.ServerOption{
2424 httptransport.ServerErrorEncoder(errorEncoder),
2525 httptransport.ServerErrorLogger(logger),
2626 }
2727 m := http.NewServeMux()
2828 m.Handle("/sum", httptransport.NewServer(
29 ctx,
3029 endpoints.SumEndpoint,
3130 DecodeHTTPSumRequest,
3231 EncodeHTTPGenericResponse,
3332 append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "Sum", logger)))...,
3433 ))
3534 m.Handle("/concat", httptransport.NewServer(
36 ctx,
3735 endpoints.ConcatEndpoint,
3836 DecodeHTTPConcatRequest,
3937 EncodeHTTPGenericResponse,
103103 // HTTP handler, and just install it under a particular path prefix in
104104 // our router.
105105
106 r.PathPrefix("/addsvc").Handler(http.StripPrefix("/addsvc", addsvc.MakeHTTPHandler(ctx, endpoints, tracer, logger)))
106 r.PathPrefix("/addsvc").Handler(http.StripPrefix("/addsvc", addsvc.MakeHTTPHandler(endpoints, tracer, logger)))
107107 }
108108
109109 // stringsvc routes.
139139 // have to do provide it with the encode and decode functions for our
140140 // stringsvc methods.
141141
142 r.Handle("/stringsvc/uppercase", httptransport.NewServer(ctx, uppercase, decodeUppercaseRequest, encodeJSONResponse))
143 r.Handle("/stringsvc/count", httptransport.NewServer(ctx, count, decodeCountRequest, encodeJSONResponse))
142 r.Handle("/stringsvc/uppercase", httptransport.NewServer(uppercase, decodeUppercaseRequest, encodeJSONResponse))
143 r.Handle("/stringsvc/count", httptransport.NewServer(count, decodeCountRequest, encodeJSONResponse))
144144 }
145145
146146 // Interrupt handler.
00 package main
11
22 import (
3 "context"
43 "flag"
54 "fmt"
65 "net/http"
2524 logger = log.NewContext(logger).With("caller", log.DefaultCaller)
2625 }
2726
28 var ctx context.Context
29 {
30 ctx = context.Background()
31 }
32
3327 var s profilesvc.Service
3428 {
3529 s = profilesvc.NewInmemService()
3832
3933 var h http.Handler
4034 {
41 h = profilesvc.MakeHTTPHandler(ctx, s, log.NewContext(logger).With("component", "HTTP"))
35 h = profilesvc.MakeHTTPHandler(s, log.NewContext(logger).With("component", "HTTP"))
4236 }
4337
4438 errs := make(chan error)
2424
2525 // MakeHTTPHandler mounts all of the service endpoints into an http.Handler.
2626 // Useful in a profilesvc server.
27 func MakeHTTPHandler(ctx context.Context, s Service, logger log.Logger) http.Handler {
27 func MakeHTTPHandler(s Service, logger log.Logger) http.Handler {
2828 r := mux.NewRouter()
2929 e := MakeServerEndpoints(s)
3030 options := []httptransport.ServerOption{
4343 // DELETE /profiles/:id/addresses/:addressID remove an address
4444
4545 r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer(
46 ctx,
4746 e.PostProfileEndpoint,
4847 decodePostProfileRequest,
4948 encodeResponse,
5049 options...,
5150 ))
5251 r.Methods("GET").Path("/profiles/{id}").Handler(httptransport.NewServer(
53 ctx,
5452 e.GetProfileEndpoint,
5553 decodeGetProfileRequest,
5654 encodeResponse,
5755 options...,
5856 ))
5957 r.Methods("PUT").Path("/profiles/{id}").Handler(httptransport.NewServer(
60 ctx,
6158 e.PutProfileEndpoint,
6259 decodePutProfileRequest,
6360 encodeResponse,
6461 options...,
6562 ))
6663 r.Methods("PATCH").Path("/profiles/{id}").Handler(httptransport.NewServer(
67 ctx,
6864 e.PatchProfileEndpoint,
6965 decodePatchProfileRequest,
7066 encodeResponse,
7167 options...,
7268 ))
7369 r.Methods("DELETE").Path("/profiles/{id}").Handler(httptransport.NewServer(
74 ctx,
7570 e.DeleteProfileEndpoint,
7671 decodeDeleteProfileRequest,
7772 encodeResponse,
7873 options...,
7974 ))
8075 r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
81 ctx,
8276 e.GetAddressesEndpoint,
8377 decodeGetAddressesRequest,
8478 encodeResponse,
8579 options...,
8680 ))
8781 r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
88 ctx,
8982 e.GetAddressEndpoint,
9083 decodeGetAddressRequest,
9184 encodeResponse,
9285 options...,
9386 ))
9487 r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
95 ctx,
9688 e.PostAddressEndpoint,
9789 decodePostAddressRequest,
9890 encodeResponse,
9991 options...,
10092 ))
10193 r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
102 ctx,
10394 e.DeleteAddressEndpoint,
10495 decodeDeleteAddressRequest,
10596 encodeResponse,
1616 )
1717
1818 // MakeHandler returns a handler for the booking service.
19 func MakeHandler(ctx context.Context, bs Service, logger kitlog.Logger) http.Handler {
19 func MakeHandler(bs Service, logger kitlog.Logger) http.Handler {
2020 opts := []kithttp.ServerOption{
2121 kithttp.ServerErrorLogger(logger),
2222 kithttp.ServerErrorEncoder(encodeError),
2323 }
2424
2525 bookCargoHandler := kithttp.NewServer(
26 ctx,
2726 makeBookCargoEndpoint(bs),
2827 decodeBookCargoRequest,
2928 encodeResponse,
3029 opts...,
3130 )
3231 loadCargoHandler := kithttp.NewServer(
33 ctx,
3432 makeLoadCargoEndpoint(bs),
3533 decodeLoadCargoRequest,
3634 encodeResponse,
3735 opts...,
3836 )
3937 requestRoutesHandler := kithttp.NewServer(
40 ctx,
4138 makeRequestRoutesEndpoint(bs),
4239 decodeRequestRoutesRequest,
4340 encodeResponse,
4441 opts...,
4542 )
4643 assignToRouteHandler := kithttp.NewServer(
47 ctx,
4844 makeAssignToRouteEndpoint(bs),
4945 decodeAssignToRouteRequest,
5046 encodeResponse,
5147 opts...,
5248 )
5349 changeDestinationHandler := kithttp.NewServer(
54 ctx,
5550 makeChangeDestinationEndpoint(bs),
5651 decodeChangeDestinationRequest,
5752 encodeResponse,
5853 opts...,
5954 )
6055 listCargosHandler := kithttp.NewServer(
61 ctx,
6256 makeListCargosEndpoint(bs),
6357 decodeListCargosRequest,
6458 encodeResponse,
6559 opts...,
6660 )
6761 listLocationsHandler := kithttp.NewServer(
68 ctx,
6962 makeListLocationsEndpoint(bs),
7063 decodeListLocationsRequest,
7164 encodeResponse,
1616 )
1717
1818 // MakeHandler returns a handler for the handling service.
19 func MakeHandler(ctx context.Context, hs Service, logger kitlog.Logger) http.Handler {
19 func MakeHandler(hs Service, logger kitlog.Logger) http.Handler {
2020 r := mux.NewRouter()
2121
2222 opts := []kithttp.ServerOption{
2525 }
2626
2727 registerIncidentHandler := kithttp.NewServer(
28 ctx,
2928 makeRegisterIncidentEndpoint(hs),
3029 decodeRegisterIncidentRequest,
3130 encodeResponse,
136136
137137 mux := http.NewServeMux()
138138
139 mux.Handle("/booking/v1/", booking.MakeHandler(ctx, bs, httpLogger))
140 mux.Handle("/tracking/v1/", tracking.MakeHandler(ctx, ts, httpLogger))
141 mux.Handle("/handling/v1/", handling.MakeHandler(ctx, hs, httpLogger))
139 mux.Handle("/booking/v1/", booking.MakeHandler(bs, httpLogger))
140 mux.Handle("/tracking/v1/", tracking.MakeHandler(ts, httpLogger))
141 mux.Handle("/handling/v1/", handling.MakeHandler(hs, httpLogger))
142142
143143 http.Handle("/", accessControl(mux))
144144 http.Handle("/metrics", stdprometheus.Handler())
1414 )
1515
1616 // MakeHandler returns a handler for the tracking service.
17 func MakeHandler(ctx context.Context, ts Service, logger kitlog.Logger) http.Handler {
17 func MakeHandler(ts Service, logger kitlog.Logger) http.Handler {
1818 r := mux.NewRouter()
1919
2020 opts := []kithttp.ServerOption{
2323 }
2424
2525 trackCargoHandler := kithttp.NewServer(
26 ctx,
2726 makeTrackCargoEndpoint(ts),
2827 decodeTrackCargoRequest,
2928 encodeResponse,
3131 }
3232
3333 func main() {
34 ctx := context.Background()
3534 svc := stringService{}
3635
3736 uppercaseHandler := httptransport.NewServer(
38 ctx,
3937 makeUppercaseEndpoint(svc),
4038 decodeUppercaseRequest,
4139 encodeResponse,
4240 )
4341
4442 countHandler := httptransport.NewServer(
45 ctx,
4643 makeCountEndpoint(svc),
4744 decodeCountRequest,
4845 encodeResponse,
00 package main
11
22 import (
3 "context"
43 "net/http"
54 "os"
65
1211 )
1312
1413 func main() {
15 ctx := context.Background()
1614 logger := log.NewLogfmtLogger(os.Stderr)
1715
1816 fieldKeys := []string{"method", "error"}
4139 svc = instrumentingMiddleware{requestCount, requestLatency, countResult, svc}
4240
4341 uppercaseHandler := httptransport.NewServer(
44 ctx,
4542 makeUppercaseEndpoint(svc),
4643 decodeUppercaseRequest,
4744 encodeResponse,
4845 )
4946
5047 countHandler := httptransport.NewServer(
51 ctx,
5248 makeCountEndpoint(svc),
5349 decodeCountRequest,
5450 encodeResponse,
2323 logger = log.NewLogfmtLogger(os.Stderr)
2424 logger = log.NewContext(logger).With("listen", *listen).With("caller", log.DefaultCaller)
2525
26 ctx := context.Background()
27
2826 fieldKeys := []string{"method", "error"}
2927 requestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{
3028 Namespace: "my_group",
4745
4846 var svc StringService
4947 svc = stringService{}
50 svc = proxyingMiddleware(*proxy, ctx, logger)(svc)
48 svc = proxyingMiddleware(context.Background(), *proxy, logger)(svc)
5149 svc = loggingMiddleware(logger)(svc)
5250 svc = instrumentingMiddleware(requestCount, requestLatency, countResult)(svc)
5351
5452 uppercaseHandler := httptransport.NewServer(
55 ctx,
5653 makeUppercaseEndpoint(svc),
5754 decodeUppercaseRequest,
5855 encodeResponse,
5956 )
6057 countHandler := httptransport.NewServer(
61 ctx,
6258 makeCountEndpoint(svc),
6359 decodeCountRequest,
6460 encodeResponse,
1919 httptransport "github.com/go-kit/kit/transport/http"
2020 )
2121
22 func proxyingMiddleware(instances string, ctx context.Context, logger log.Logger) ServiceMiddleware {
22 func proxyingMiddleware(ctx context.Context, instances string, logger log.Logger) ServiceMiddleware {
2323 // If instances is empty, don't proxy.
2424 if instances == "" {
2525 logger.Log("proxy_to", "none")
88
99 func ExamplePopulateRequestContext() {
1010 handler := NewServer(
11 context.Background(),
1211 func(ctx context.Context, request interface{}) (response interface{}, err error) {
1312 fmt.Println("Method", ctx.Value(ContextKeyRequestMethod).(string))
1413 fmt.Println("RequestPath", ctx.Value(ContextKeyRequestPath).(string))
1010
1111 // Server wraps an endpoint and implements http.Handler.
1212 type Server struct {
13 ctx context.Context
1413 e endpoint.Endpoint
1514 dec DecodeRequestFunc
1615 enc EncodeResponseFunc
2423 // NewServer constructs a new server, which implements http.Server and wraps
2524 // the provided endpoint.
2625 func NewServer(
27 ctx context.Context,
2826 e endpoint.Endpoint,
2927 dec DecodeRequestFunc,
3028 enc EncodeResponseFunc,
3129 options ...ServerOption,
3230 ) *Server {
3331 s := &Server{
34 ctx: ctx,
3532 e: e,
3633 dec: dec,
3734 enc: enc,
8481
8582 // ServeHTTP implements http.Handler.
8683 func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
87 ctx := s.ctx
84 ctx := r.Context()
8885
8986 if s.finalizer != nil {
9087 iw := &interceptingWriter{w, http.StatusOK, 0}
1515
1616 func TestServerBadDecode(t *testing.T) {
1717 handler := httptransport.NewServer(
18 context.Background(),
1918 func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
2019 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, errors.New("dang") },
2120 func(context.Context, http.ResponseWriter, interface{}) error { return nil },
3029
3130 func TestServerBadEndpoint(t *testing.T) {
3231 handler := httptransport.NewServer(
33 context.Background(),
3432 func(context.Context, interface{}) (interface{}, error) { return struct{}{}, errors.New("dang") },
3533 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
3634 func(context.Context, http.ResponseWriter, interface{}) error { return nil },
4543
4644 func TestServerBadEncode(t *testing.T) {
4745 handler := httptransport.NewServer(
48 context.Background(),
4946 func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil },
5047 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
5148 func(context.Context, http.ResponseWriter, interface{}) error { return errors.New("dang") },
6764 return http.StatusInternalServerError
6865 }
6966 handler := httptransport.NewServer(
70 context.Background(),
7167 func(context.Context, interface{}) (interface{}, error) { return struct{}{}, errTeapot },
7268 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
7369 func(context.Context, http.ResponseWriter, interface{}) error { return nil },
8278 }
8379
8480 func TestServerHappyPath(t *testing.T) {
85 _, step, response := testServer(t)
81 step, response := testServer(t)
8682 step()
8783 resp := <-response
8884 defer resp.Body.Close()
9187 t.Errorf("want %d, have %d (%s)", want, have, buf)
9288 }
9389 }
94
9590
9691 func TestMultipleServerBefore(t *testing.T) {
9792 var (
10297 done = make(chan struct{})
10398 )
10499 handler := httptransport.NewServer(
105 context.Background(),
106100 endpoint.Nop,
107101 func(context.Context, *http.Request) (interface{}, error) {
108102 return struct{}{}, nil
148142 done = make(chan struct{})
149143 )
150144 handler := httptransport.NewServer(
151 context.Background(),
152145 endpoint.Nop,
153146 func(context.Context, *http.Request) (interface{}, error) {
154147 return struct{}{}, nil
194187 done = make(chan struct{})
195188 )
196189 handler := httptransport.NewServer(
197 context.Background(),
198190 endpoint.Nop,
199191 func(context.Context, *http.Request) (interface{}, error) {
200192 return struct{}{}, nil
244236
245237 func TestEncodeJSONResponse(t *testing.T) {
246238 handler := httptransport.NewServer(
247 context.Background(),
248239 func(context.Context, interface{}) (interface{}, error) { return enhancedResponse{Foo: "bar"}, nil },
249240 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
250241 httptransport.EncodeJSONResponse,
275266
276267 func TestEncodeNoContent(t *testing.T) {
277268 handler := httptransport.NewServer(
278 context.Background(),
279269 func(context.Context, interface{}) (interface{}, error) { return noContentResponse{}, nil },
280270 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
281271 httptransport.EncodeJSONResponse,
306296
307297 func TestEnhancedError(t *testing.T) {
308298 handler := httptransport.NewServer(
309 context.Background(),
310299 func(context.Context, interface{}) (interface{}, error) { return nil, enhancedError{} },
311300 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
312301 func(_ context.Context, w http.ResponseWriter, _ interface{}) error { return nil },
332321 }
333322 }
334323
335 func testServer(t *testing.T) (cancel, step func(), resp <-chan *http.Response) {
324 func testServer(t *testing.T) (step func(), resp <-chan *http.Response) {
336325 var (
337 ctx, cancelfn = context.WithCancel(context.Background())
338 stepch = make(chan bool)
339 endpoint = func(context.Context, interface{}) (interface{}, error) { <-stepch; return struct{}{}, nil }
340 response = make(chan *http.Response)
341 handler = httptransport.NewServer(
342 ctx,
326 stepch = make(chan bool)
327 endpoint = func(context.Context, interface{}) (interface{}, error) { <-stepch; return struct{}{}, nil }
328 response = make(chan *http.Response)
329 handler = httptransport.NewServer(
343330 endpoint,
344331 func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
345332 func(context.Context, http.ResponseWriter, interface{}) error { return nil },
357344 }
358345 response <- resp
359346 }()
360 return cancelfn, func() { stepch <- true }, response
361 }
347 return func() { stepch <- true }, response
348 }