mirror of https://github.com/gin-gonic/gin.git
feat: Added Params.GetInt method & Context.ParamInt method
This commit is contained in:
parent
cc4e11438c
commit
002f8bc70d
11
context.go
11
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"
|
||||
|
|
|
@ -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")
|
||||
|
|
13
tree.go
13
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
|
||||
|
|
Loading…
Reference in New Issue