github.com/lingyao2333/mo-zero@v1.4.1/rest/pathvar/params.go (about)

     1  package pathvar
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  )
     7  
     8  var pathVars = contextKey("pathVars")
     9  
    10  // Vars parses path variables and returns a map.
    11  func Vars(r *http.Request) map[string]string {
    12  	vars, ok := r.Context().Value(pathVars).(map[string]string)
    13  	if ok {
    14  		return vars
    15  	}
    16  
    17  	return nil
    18  }
    19  
    20  // WithVars writes params into given r and returns a new http.Request.
    21  func WithVars(r *http.Request, params map[string]string) *http.Request {
    22  	return r.WithContext(context.WithValue(r.Context(), pathVars, params))
    23  }
    24  
    25  type contextKey string
    26  
    27  func (c contextKey) String() string {
    28  	return "rest/pathvar/context key: " + string(c)
    29  }