go-zero/rest/pathvar/params.go

30 lines
622 B
Go
Raw Normal View History

package pathvar
2020-07-29 18:00:04 +08:00
import (
"context"
"net/http"
)
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
}
// 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))
}
type contextKey string
func (c contextKey) String() string {
return "rest/pathvar/context key: " + string(c)
}