2021-08-14 22:57:28 +08:00
|
|
|
package pathvar
|
2020-07-29 18:00:04 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2020-09-20 12:46:35 +08:00
|
|
|
var pathVars = contextKey("pathVars")
|
2020-07-29 18:00:04 +08:00
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// Vars parses path variables and returns a map.
|
2020-07-29 18:00:04 +08:00
|
|
|
func Vars(r *http.Request) map[string]string {
|
|
|
|
vars, ok := r.Context().Value(pathVars).(map[string]string)
|
|
|
|
if ok {
|
|
|
|
return vars
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-14 22:57:28 +08:00
|
|
|
// WithVars writes params into given r and returns a new http.Request.
|
|
|
|
func WithVars(r *http.Request, params map[string]string) *http.Request {
|
2020-07-29 18:00:04 +08:00
|
|
|
return r.WithContext(context.WithValue(r.Context(), pathVars, params))
|
|
|
|
}
|
2020-09-20 12:46:35 +08:00
|
|
|
|
|
|
|
type contextKey string
|
|
|
|
|
|
|
|
func (c contextKey) String() string {
|
2021-08-14 22:57:28 +08:00
|
|
|
return "rest/pathvar/context key: " + string(c)
|
2020-09-20 12:46:35 +08:00
|
|
|
}
|