vars.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package myth
  2. import (
  3. "context"
  4. "net/http"
  5. )
  6. type contextKey string
  7. const (
  8. varsKey contextKey = `httprouter_route_vars`
  9. routeKey = `httprouter_route_path`
  10. )
  11. // ContextVars returns the route variables for the current Context, if any.
  12. func ContextVars(ctx context.Context) map[string]string {
  13. if rv := ctx.Value(varsKey); rv != nil {
  14. return rv.(map[string]string)
  15. }
  16. return nil
  17. }
  18. // ContextRoutePath current route
  19. func ContextRoutePath(ctx context.Context) string {
  20. if rv := ctx.Value(routeKey); rv != nil {
  21. return rv.(string)
  22. }
  23. return ""
  24. }
  25. // Vars returns the route variables for the current request, if any.
  26. func Vars(r *http.Request) map[string]string {
  27. if rv := contextGet(r, varsKey); rv != nil {
  28. return rv.(map[string]string)
  29. }
  30. return nil
  31. }
  32. func setVars(r *http.Request, val interface{}) *http.Request {
  33. return contextSet(r, varsKey, val)
  34. }
  35. func setCurrentPath(r *http.Request, val interface{}) *http.Request {
  36. return contextSet(r, routeKey, val)
  37. }
  38. func contextGet(r *http.Request, key interface{}) interface{} {
  39. return r.Context().Value(key)
  40. }
  41. func contextSet(r *http.Request, key, val interface{}) *http.Request {
  42. if val == nil {
  43. return r
  44. }
  45. return r.WithContext(context.WithValue(r.Context(), key, val))
  46. }
  47. func contextClear(r *http.Request) {
  48. return
  49. }