github.com/koko1123/flow-go-1@v0.29.6/engine/access/rest/middleware/common_query_params.go (about) 1 package middleware 2 3 import ( 4 "net/http" 5 "strings" 6 7 "github.com/gorilla/mux" 8 ) 9 10 const ExpandQueryParam = "expand" 11 const selectQueryParam = "select" 12 13 // commonQueryParamMiddleware generates a Middleware function that extracts the given query parameter from the request 14 // and adds it to the request context as a key value pair with the key as the query param name. 15 // e.g. for queryParamName "fields", if the request url contains <some url>?fields=field1,field2,..fieldN, 16 // the middleware returned by commonQueryParamMiddleware will add the key - "fields" to the request context with value 17 // as a map containing each of the field as key and value true ["field"]->true, ["fields2"] -> true etc when it is executed 18 func commonQueryParamMiddleware(queryParamName string) mux.MiddlewareFunc { 19 return func(handler http.Handler) http.Handler { 20 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 21 if value, ok := req.URL.Query()[queryParamName]; ok { 22 if len(value) > 0 && len(value[0]) > 0 { 23 values := strings.Split(value[0], ",") 24 // save the query param value in the request context 25 req = addRequestAttribute(req, queryParamName, values) 26 } 27 } 28 handler.ServeHTTP(w, req) 29 }) 30 } 31 } 32 33 // QueryExpandable middleware extracts out the 'expand' query param field if present in the request 34 func QueryExpandable() mux.MiddlewareFunc { 35 return commonQueryParamMiddleware(ExpandQueryParam) 36 } 37 38 // QuerySelect middleware extracts out the 'select' query param field if present in the request 39 func QuerySelect() mux.MiddlewareFunc { 40 return commonQueryParamMiddleware(selectQueryParam) 41 } 42 43 func getField(req *http.Request, key string) ([]string, bool) { 44 value, found := getRequestAttribute(req, key) 45 if !found { 46 return nil, false 47 } 48 valueAsStringSlice, ok := value.([]string) 49 return valueAsStringSlice, ok 50 } 51 52 func GetFieldsToExpand(req *http.Request) ([]string, bool) { 53 return getField(req, ExpandQueryParam) 54 } 55 56 func GetFieldsToSelect(req *http.Request) ([]string, bool) { 57 return getField(req, selectQueryParam) 58 }