| OLD | NEW |
| (Empty) |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package ephelper | |
| 6 | |
| 7 import ( | |
| 8 "fmt" | |
| 9 | |
| 10 "github.com/GoogleCloudPlatform/go-endpoints/endpoints" | |
| 11 "golang.org/x/net/context" | |
| 12 ) | |
| 13 | |
| 14 type serviceCallKeyType int | |
| 15 | |
| 16 var serviceCallKey serviceCallKeyType | |
| 17 | |
| 18 type serviceCall struct { | |
| 19 mi *endpoints.MethodInfo | |
| 20 } | |
| 21 | |
| 22 // ServiceBase is an embeddable base class for endpoints services. | |
| 23 // | |
| 24 // Example: | |
| 25 // | |
| 26 // type MyService struct { | |
| 27 // *ServiceBase | |
| 28 // } | |
| 29 // | |
| 30 // func (s *MyService) MyCoolEndpoint(c context.Context) error { | |
| 31 // c, err = s.Use(c, myMethodInfo) | |
| 32 // if err != nil { | |
| 33 // return err | |
| 34 // } | |
| 35 // ... | |
| 36 // } | |
| 37 type ServiceBase struct { | |
| 38 // Middleware is the set of middleware context manipulators to run for t
his | |
| 39 // service. | |
| 40 // | |
| 41 // If nil, the middleware stack returned by DefaultMiddleware will be us
ed. | |
| 42 Middleware []Middleware | |
| 43 } | |
| 44 | |
| 45 // Use should be called at the beginning of a Cloud Endpoint handler to | |
| 46 // initialize the handler's baseline Context and authenticate the call. | |
| 47 func (s *ServiceBase) Use(c context.Context, mi *endpoints.MethodInfo) (context.
Context, error) { | |
| 48 // In case the developer forgot to set it... | |
| 49 if s == nil { | |
| 50 return c, fmt.Errorf("no ServiceBase is configured for: %#v", mi
) | |
| 51 } | |
| 52 | |
| 53 // Embed our service context. | |
| 54 sc := serviceCall{ | |
| 55 mi: mi, | |
| 56 } | |
| 57 c = context.WithValue(c, serviceCallKey, &sc) | |
| 58 | |
| 59 middleware := s.Middleware | |
| 60 if middleware == nil { | |
| 61 middleware = []Middleware{DefaultMiddleware(nil)} | |
| 62 } | |
| 63 for _, mw := range middleware { | |
| 64 ic, err := mw(c) | |
| 65 if err != nil { | |
| 66 return c, err | |
| 67 } | |
| 68 c = ic | |
| 69 } | |
| 70 | |
| 71 return c, nil | |
| 72 } | |
| 73 | |
| 74 // MethodInfo returns the endpoints.MethodInfo for the current service call. | |
| 75 func MethodInfo(c context.Context) *endpoints.MethodInfo { | |
| 76 if sc, ok := c.Value(serviceCallKey).(*serviceCall); ok { | |
| 77 return sc.mi | |
| 78 } | |
| 79 return nil | |
| 80 } | |
| OLD | NEW |