获取GET请求参数
func main() {
router := gin.Default()
// Query string parameters are parsed using the existing underlying request object.
// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {
//查询请求URL后面的参数,如果没有填写默认值
firstname := c.DefaultQuery("firstname", "Guest")
//查询请求URL后面的参数
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run(":8080")
}
如下图请求方式以键的形式和路径进行拼接
获取POST请求参数
func main() {
router := gin.Default()
router.POST("/form_post", func(c *gin.Context) {
//从表单中查询参数
message := c.PostForm("message")
//从表单中查询参数,,如果没有就获取默认值
nick := c.DefaultPostForm("nick", "anonymous")
c.JSON(200, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
})
router.Run(":8080")
}
如下图请求方式以键的形式和路径进行拼接
获取Body值
package main
import (
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
)
func main() {
router := gin.Default()
router.POST("/user/*action", func(c *gin.Context) {
bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
c.String(http.StatusOK, string(bodyBytes))
})
router.Run(":8080")
}
获取路径中的参数
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 此规则能够匹配/user/john这种格式,但不能匹配/user/ 或 /user这种格式
router.GET("/user/:name", func(c *gin.Context) {
//从表单中查询参数
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// 但是,这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
// 如果没有其他路由器匹配/user/john,它将重定向到/user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}
请求方式如下图
未完待续~