Gin之获取path参数
注:本文基于Windos系统上Go SDK v1.17.5、github.com/gin-gonic/gin v1.7.7依赖进行讲解
1.path参数介绍
path:即URL路径参数
2.获取一个":"path参数(Param方法)
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/users/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"id": id,
})
})
r.Run(":8080")
}
3. 获取二个":"path参数(Param方法)
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/user/search/:username/:address", func(c *gin.Context) {
username := c.Param("username") //
address := c.Param("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
r.Run(":8080")
}
4.获取"*"path参数(Param方法)
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/user/search/:username/*address", func(c *gin.Context) {
username := c.Param("username")
address := c.Param("address")
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"username": username,
"address": address,
})
})
r.Run(":8080")
}
如果访问http://localhost:8080/user/search/:dafa的换,系统会被重定向到http://localhost:8080/user/search/:dafa/,浏览器并且输出:{“address”:“/”,“message”:“ok”,“username”:“:dafa”}
如果单独访问http://localhost:8080/user/search/:dafa/的话,浏览器输出:{“address”:“/”,“message”:“ok”,“username”:“:dafa”}
5.获取一个":"path参数(ShouldBindUri方法)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
_ "github.com/gin-gonic/gin/binding"
)
type Person struct {
Id string `uri:"id"`
}
func startPage(c *gin.Context) {
var person Person
t := c.ShouldBindUri(&person)
if t != nil {
fmt.Println(t)
}
fmt.Println(person.Id)
c.String(200, "Success")
}
func main() {
r := gin.Default()
r.GET("/user/:id", startPage)
r.Run()
}