github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/middleware/region.go (about)

     1  package middleware
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"github.com/gorilla/mux"
     8  )
     9  
    10  // The key type is no exported to prevent collisions with context keys
    11  // defined in other packages.
    12  type key int
    13  
    14  const (
    15  	// requestRegionKey is the context key for the region from the request path.
    16  	requestRegionKey key = iota + 1
    17  )
    18  
    19  func AddRegionToContext(defaultRegion string) mux.MiddlewareFunc {
    20  	return func(next http.Handler) http.Handler {
    21  		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    22  			vars := mux.Vars(req)
    23  			region, found := vars["region"]
    24  			if !found {
    25  				region = defaultRegion
    26  			}
    27  
    28  			newCtx := context.WithValue(req.Context(), requestRegionKey, region)
    29  			next.ServeHTTP(w, req.WithContext(newCtx))
    30  		})
    31  	}
    32  }
    33  
    34  // RegionFromContext returns request region associated with the context if possible.
    35  func RegionFromContext(ctx context.Context) (string, bool) {
    36  	region, ok := ctx.Value(requestRegionKey).(string)
    37  	return region, ok
    38  }