在Gin框架中,可以通过Query来获取URL中?后面所携带的参数。例如/name=admin&pwd=123456
。获取方法如下
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
name := c.Query("name")
pwd := c.Query("pwd")
// fmt.Printf("name:%s ; pwd:%s",name,pwd)
c.JSON(http.StatusOK, gin.H{
"name": name,
"pwd": pwd,
})
})
r.Run()
}
当前端请求的数据通过form表单提交时,例如向/user/reset
发送了一个POST请求,获取请求数据方法如下
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("./login.html", "./index.html") //加载页面
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
r.POST("/", func(c *gin.Context) {
username := c.PostForm("username") //对应h5表单中的name字段
password := c.PostForm("password")
c.HTML(http.StatusOK, "index.html", gin.H{
"username": username,
"password": password,
})
})
r.Run()
}
请求的参数通过URL路径传递,例如/user/admin
,获取请求URL路径中的参数方法如下
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/user/:username", func(c *gin.Context) {
username := c.Param("username")
c.JSON(http.StatusOK, gin.H{
"username": username,
})
})
r.Run()
}