github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/middleware/provider.go (about) 1 package middleware 2 3 import ( 4 "context" 5 "net/http" 6 "regexp" 7 8 "github.com/gorilla/mux" 9 10 "github.com/kyma-project/kyma-environment-broker/internal" 11 ) 12 13 // The providerKey type is no exported to prevent collisions with context keys 14 // defined in other packages. 15 type providerKey int 16 17 const ( 18 // requestRegionKey is the context key for the region from the request path. 19 requestProviderKey providerKey = iota + 1 20 ) 21 22 func AddProviderToContext() mux.MiddlewareFunc { 23 return func(next http.Handler) http.Handler { 24 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 25 vars := mux.Vars(req) 26 region, found := vars["region"] 27 provider := internal.UnknownProvider 28 if found { 29 provider = platformProvider(region) 30 } 31 32 newCtx := context.WithValue(req.Context(), requestProviderKey, provider) 33 next.ServeHTTP(w, req.WithContext(newCtx)) 34 }) 35 } 36 } 37 38 // ProviderFromContext returns request provider associated with the context if possible. 39 func ProviderFromContext(ctx context.Context) (internal.CloudProvider, bool) { 40 provider, ok := ctx.Value(requestProviderKey).(internal.CloudProvider) 41 return provider, ok 42 } 43 44 var platformRegionProviderRE = regexp.MustCompile("[0-9]") 45 46 func platformProvider(region string) internal.CloudProvider { 47 if region == "" { 48 return internal.UnknownProvider 49 } 50 digit := platformRegionProviderRE.FindString(region) 51 switch digit { 52 case "1": 53 return internal.AWS 54 case "2": 55 return internal.Azure 56 default: 57 return internal.UnknownProvider 58 } 59 }