Gin GET POST 以及获取GET POST传值
1Get 请求传值
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// http://127.0.0.1:8000/query?username=111&age=10&sex=
// {"age":"10","sex":"","username":"111"}
// http://127.0.0.1:8000/query?username=111&age=10
// {"age":"10","sex":"0","username":"111"}
r.GET("/query", func(c *gin.Context) {
username := c.Query("username")
age := c.Query("age")
sex := c.DefaultQuery("sex", "0") // 如果不传值 则使用默认值
c.JSON(http.StatusOK, gin.H{
"username": username,
"age": age,
"sex": sex,
})
})
r.Run(":8000")
}
2.POST取值
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.POST("/add", func(c *gin.Context) {
username := c.PostForm("username")
age := c.PostForm("age")
sex := c.DefaultPostForm("sex", "1")
c.JSON(http.StatusOK, gin.H{
"username": username,
"age": age,
"sex": sex,
})
})
r.Run(":8000")
}
3 将GET或者POST的数据绑定到结构体上
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type UserInfo struct {
Username string `json:"username" form:"username"` // 需要用到form标签,需要和传过来的key相同
Age string `json:"age" form:"age"`
Sex string `json:"sex" form:"sex"`
}
func main() {
r := gin.Default()
r.POST("/add1", func(c *gin.Context) {
userinfo := UserInfo{}
if err := c.ShouldBind(&userinfo); err != nil {
c.JSON(http.StatusOK, gin.H{
"err": err.Error(),
})
} else {
c.JSON(http.StatusOK, userinfo)
}
})
r.GET("/add2", func(c *gin.Context) {
userinfo := UserInfo{}
if err := c.ShouldBind(&userinfo); err != nil {
c.JSON(http.StatusOK, gin.H{
"err": err.Error(),
})
} else {
c.JSON(http.StatusOK, userinfo)
}
})
r.Run(":8000")
}
4 获取Post Xml数据
在API的开发中,我们经常会用到JSON或XML来作为数据交互的格式,这个时候我们可以在gin中使用c.GetRawData()获取数据。
<?xml version="1.0" encoding="UTF-8"?>
<userinfo>
<username type="string">我是张三</username>
<age type="string">20</age>
<sex type="string">88888</sex>
</userinfo>
package main
import (
"encoding/xml"
"net/http"
"github.com/gin-gonic/gin"
)
type UserInfo struct {
Username string `json:"username" form:"username" xml:"username"` // 需要使用到xml标签,名称与传递过来的xml中的标签名称相同
Age string `json:"age" form:"age" xml:"age"`
Sex string `json:"sex" form:"sex" xml:"sex"`
}
func main() {
r := gin.Default()
r.POST("/postxml", func(c *gin.Context) {
xmldata, _ := c.GetRawData() // 从c.Request.Body 读取请求数据
userinfo := UserInfo{}
if err := xml.Unmarshal(xmldata, &userinfo); err != nil {
c.JSON(http.StatusOK, gin.H{
"err": err.Error(),
})
}
c.JSON(http.StatusOK, userinfo)
})
r.Run(":8000")
}
5 动态路由传值
package main
import (
"encoding/xml"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/uer/:uid", func(c *gin.Context) {
uid := c.Param("uid")
c.String(http.StatusOK, uid)
})
r.Run(":8000")
}