gin获取URL路径参数
package main
//获取path(URL)参数
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/:name/:age", func(c *gin.Context) {
//获取路径参数
name := c.Param("name")
age := c.Param("age")
c.JSON(http.StatusOK, gin.H{
"name": name,
"age": age,
})
})
r.Run(":9090")
}
参数绑定
原来代码很累
package main
//获取path(URL)参数
import (
"fmt"
"net/http"
"os/user"
"github.com/gin-gonic/gin"
)
type UserInfo struct{
username string
password string
}
func main() {
r := gin.Default()
r.GET("/user", func(c *gin.Context) {
username := c.Query("username")
password := c.Query("password")
u := UserInfo{
username: username,
password: password,
}
fmt.Printf("%#v\n",u)
c.JSON(http.StatusOK,gin.H{
"massage" : "ok",
})
})
})
r.Run(":9090")
}
现在:
shouldbind非常强大,三种方式都能获取参数
package main
//获取path(URL)参数
import (
"fmt"
"net/http"
"os/user"
"github.com/gin-gonic/gin"
)
type UserInfo struct{
Username string `form:"username"`
Password string `form:"password"`
}
func main() {
r := gin.Default()
r.GET("/user", func(c *gin.Context) {
var u UserInfo
err := c.ShouldBind(u)
if err != nil{
c.JSON(http.StatusBadRequest,gin.H{
"error" : err.Error(),
})
}else{
//用到反射,我不知道用户给我传进来什么字段,要用反射动态获取
fmt.Printf("%#v\n",&u)
c.JSON(http.StatusOK,gin.H{
"status":"ok",
})
}
})
})
r.Run(":9090")
}