M example_test.go => example_test.go +2 -2
@@ 15,7 15,7 @@ import (
func Example_path() {
m := mux.New(
mux.HandleFunc("GET", "/sha256/{wildcard path}", func(w http.ResponseWriter, r *http.Request) {
- val, _ := mux.Param(r, "wildcard")
+ val := mux.Param(r, "wildcard")
sum := sha256.Sum256([]byte(val.Raw))
fmt.Fprintf(w, "the hash of %q is %x", val.Raw, sum)
}),
@@ 36,7 36,7 @@ func Example_path() {
func Example_normalization() {
m := mux.New(
mux.HandleFunc("GET", "/profile/{username string}/personal", func(w http.ResponseWriter, r *http.Request) {
- username, _ := mux.Param(r, "username")
+ username := mux.Param(r, "username")
// You probably want to use the Username Case Mapped profile from the
// golang.org/x/text/secure/precis package instead of lowercasing.
normalized := strings.ToLower(username.Raw)
M norm.go => norm.go +4 -4
@@ 19,8 19,8 @@ var (
// Because WithParam is used to normalize request parameters after the route
// has already been resolved, all replaced parameters are of type string.
func WithParam(r *http.Request, name, val string) *http.Request {
- pinfo, ok := Param(r, name)
- if !ok {
+ pinfo := Param(r, name)
+ if pinfo.Value == nil {
return r
}
@@ 80,8 80,8 @@ func Path(r *http.Request) (string, error) {
return "", err
}
default:
- pinfo, ok := Param(r, name)
- if !ok {
+ pinfo := Param(r, name)
+ if pinfo.Value == nil {
return "", errNoParam
}
_, err = canonicalPath.WriteString(pinfo.Raw)
M params.go => params.go +4 -5
@@ 10,6 10,7 @@ type ctxParam string
// ParamInfo represents a route parameter and related metadata.
type ParamInfo struct {
// The parsed value of the parameter (for example int64(10))
+ // If and only if no such parameter existed on the route, Value will be nil.
Value interface{}
// The raw value of the parameter (for example "10")
Raw string
@@ 27,10 28,8 @@ type ParamInfo struct {
}
// Param returns the named route parameter from the requests context.
-func Param(r *http.Request, name string) (pinfo ParamInfo, ok bool) {
+func Param(r *http.Request, name string) ParamInfo {
v := r.Context().Value(ctxParam(name))
- if v == nil {
- return ParamInfo{}, false
- }
- return v.(ParamInfo), true
+ pinfo, _ := v.(ParamInfo)
+ return pinfo
}
M params_test.go => params_test.go +4 -4
@@ 114,8 114,8 @@ func paramsHandler(t *testing.T, params []mux.ParamInfo) http.HandlerFunc {
w.WriteHeader(testStatusCode)
for _, v := range params {
- pinfo, ok := mux.Param(r, v.Name)
- if !ok {
+ pinfo := mux.Param(r, v.Name)
+ if pinfo.Value == nil {
t.Errorf("No such parameter found %q", v.Name)
continue
}
@@ 166,8 166,8 @@ func TestParams(t *testing.T) {
}
func TestParamNotFound(t *testing.T) {
- pinfo, ok := mux.Param(httptest.NewRequest("GET", "/", nil), "badparam")
- if ok {
+ pinfo := mux.Param(httptest.NewRequest("GET", "/", nil), "badparam")
+ if pinfo.Value != nil {
t.Errorf("Did not expect to find param but got %+v", pinfo)
}
}