diff --git a/context.go b/context.go index baa4b0f9..5756b8fe 100644 --- a/context.go +++ b/context.go @@ -412,6 +412,17 @@ func (c *Context) Param(key string) string { return c.Params.ByName(key) } +// ParamInt returns the value of the URL param as an int. +// It is a shortcut for c.Params.GetInt(key) +// +// router.GET("/user/:id", func(c *gin.Context) { +// // a GET request to /user/32 +// id := c.Param("id") // id == "32" +// }) +func (c *Context) ParamInt(key string) int { + return c.Params.GetInt(key) +} + // AddParam adds param to context and // replaces path param key with given value for e2e testing purposes // Example Route: "/user/:id" diff --git a/routes_test.go b/routes_test.go index d6233b09..94b4a918 100644 --- a/routes_test.go +++ b/routes_test.go @@ -683,13 +683,13 @@ func TestRouteRawPath(t *testing.T) { route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") - num := c.Params.ByName("num") + num := c.Params.GetInt("num") assert.Equal(t, name, c.Param("name")) - assert.Equal(t, num, c.Param("num")) + assert.Equal(t, num, c.ParamInt("num")) assert.Equal(t, "Some/Other/Project", name) - assert.Equal(t, "222", num) + assert.Equal(t, 222, num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/222") @@ -703,13 +703,13 @@ func TestRouteRawPathNoUnescape(t *testing.T) { route.POST("/project/:name/build/:num", func(c *Context) { name := c.Params.ByName("name") - num := c.Params.ByName("num") + num := c.Params.GetInt("num") assert.Equal(t, name, c.Param("name")) - assert.Equal(t, num, c.Param("num")) + assert.Equal(t, num, c.ParamInt("num")) assert.Equal(t, "Some%2FOther%2FProject", name) - assert.Equal(t, "333", num) + assert.Equal(t, 333, num) }) w := PerformRequest(route, http.MethodPost, "/project/Some%2FOther%2FProject/build/333") diff --git a/tree.go b/tree.go index b0a5f982..19460d53 100644 --- a/tree.go +++ b/tree.go @@ -7,6 +7,7 @@ package gin import ( "bytes" "net/url" + "strconv" "strings" "unicode" "unicode/utf8" @@ -49,6 +50,18 @@ func (ps Params) ByName(name string) (va string) { return } +// GetInt returns the param associated with the name as an integer. +func (ps Params) GetInt(name string) (i int) { + if val, exist := ps.Get(name); exist { + i, err := strconv.Atoi(val) + if err != nil { + return 0 + } + return i + } + return +} + type methodTree struct { method string root *node