params.go 631 B

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