文章目录
Gin之获取JSON参数
注:本文基于Windos系统上Go SDK v1.17.5、github.com/gin-gonic/gin v1.7.7依赖进行讲解
1.获取JSON参数(ShouldBind方法)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Username string `form:"username" json:"user"`
Password string `form:"password" json:"pass"`
}
func main() {
r := gin.Default()
r.POST("/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()
}
注:raw代表的是原始数据,这四行内容是自己写进去的
2.获取JSON参数(ShouldBind方法)
package main
import (
"github.com/gin-gonic/gin"
_ "github.com/gin-gonic/gin/binding"
"log"
)
type Person struct {
Name string `json:"name"`
Address string `json:"address"`
}
func startPage(c *gin.Context) {
var person Person
if c.ShouldBind(&person) == nil {
log.Println(person.Name)
log.Println(person.Address)
}
c.String(200, "Success")
}
func main() {
r := gin.Default()
r.POST("/user", startPage)
r.Run()
}
3.获取JSON参数(ShouldBind方法)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Username string `form:"username"`
Password string `form:"password"`
}
func main() {
r := gin.Default()
r.POST("/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()
}
注:raw代表的是原始数据,这四行内容是自己写进去的
4.获取JSON参数(ShouldBind方法)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Username string `json:"username"`
Password string `json:"password"`
}
func main() {
r := gin.Default()
r.POST("/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()
}
5.获取JSON参数(ShouldBind方法)
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
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()
}