Skip to content

Commit

Permalink
Merge pull request #103 from danielgtaylor/iw/require-path-params
Browse files Browse the repository at this point in the history
fix: enforce path params are required
  • Loading branch information
iwong-isp authored May 16, 2023
2 parents d1d01e5 + b42a8c2 commit 62c3193
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 8 additions & 1 deletion resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,14 @@ func setFields(ctx *hcontext, req *http.Request, input reflect.Value, t reflect.
if name, ok := f.Tag.Lookup(locationPath); ok {
pname = name
location = locationPath
if v := chi.URLParam(req, name); v != "" {
v := chi.URLParam(req, name)
if v == "" {
ctx.AddError(&ErrorDetail{
Message: fmt.Sprintf("%s is required", name),
Location: location + "." + name,
Value: v,
})
} else {
pv = v
}
}
Expand Down
21 changes: 21 additions & 0 deletions resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,24 @@ func TestRawBody(t *testing.T) {

assert.Equal(t, http.StatusUnprocessableEntity, w.Result().StatusCode)
}

type PathParamTestModel struct {
TestParam string `path:"test-id"`
}

func TestPathParamAlwaysRequired(t *testing.T) {
app := newTestRouter()

app.Resource("/test/{test-id}/foo").Get("test", "Test",
NewResponse(http.StatusOK, "desc"),
).Run(func(ctx Context, input PathParamTestModel) {
ctx.WriteHeader(http.StatusOK)
})

w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/test//foo", nil)
app.ServeHTTP(w, r)

assert.Equal(t, http.StatusBadRequest, w.Result().StatusCode)
assert.Contains(t, w.Body.String(), "test-id is required")
}

0 comments on commit 62c3193

Please sign in to comment.