check parameter in path

This commit is contained in:
wu.sphinx 2017-12-21 22:25:17 +08:00
parent a816f9e9db
commit ec8d4ee42e
2 changed files with 27 additions and 0 deletions

8
gin.go
View File

@ -21,6 +21,7 @@ const (
) )
var ( var (
default400Body = []byte("400 parameter invalid")
default404Body = []byte("404 page not found") default404Body = []byte("404 page not found")
default405Body = []byte("405 method not allowed") default405Body = []byte("405 method not allowed")
defaultAppEngine bool defaultAppEngine bool
@ -346,6 +347,13 @@ func (engine *Engine) handleHTTPRequest(c *Context) {
root := t[i].root root := t[i].root
// Find route in tree // Find route in tree
handlers, params, tsr := root.getValue(path, c.Params, unescape) handlers, params, tsr := root.getValue(path, c.Params, unescape)
// Check parameter in path
for _, item := range params {
if ":"+item.Key == item.Value {
serveError(c, http.StatusBadRequest, default400Body)
return
}
}
if handlers != nil { if handlers != nil {
c.handlers = handlers c.handlers = handlers
c.Params = params c.Params = params

View File

@ -133,3 +133,22 @@ func TestWithHttptestWithAutoSelectedPort(t *testing.T) {
// testRequest(t, "http://localhost:8033/example") // testRequest(t, "http://localhost:8033/example")
// } // }
func TestParameterInPath(t *testing.T) {
router := New()
go func() {
router.GET("/user/:name", func(c *Context) { c.String(http.StatusOK, "it worked") })
assert.NoError(t, router.Run(":4123"))
}()
// have to wait for the goroutine to start and run the server
// otherwise the main thread will complete
time.Sleep(5 * time.Millisecond)
resp, err := http.Get("http://localhost:4123/user/:name")
assert.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, "400 Bad Request", resp.Status, "should get a 400")
testRequest(t, "http://localhost:4123/user/gin")
}