JSON数据解析和绑定 ShouldBindJSON

客户端传参,后端解析绑定

```go package main

import ( “github.com/gin-gonic/gin” “net/http” )

type Login struct { UserName string form:"username" json:"username" uri:"username" xml:"username" binding:"required" Password string form:"password" json:"password" uri:"password" xml:"password" binding:"required" }

func main() { //创建路由 r := gin.Default() //创建POST请求 r.POST(“/login”, func(context *gin.Context) { var login Login //把body映射到结构体里面取 if err := context.ShouldBindJSON(&login); err != nil { context.JSON(http.StatusBadRequest, gin.H{“error”: err.Error()}) return } if login.UserName != “root” || login.Password != “admin” { context.JSON(http.StatusBadRequest, gin.H{“status”: “304”}) return } //返回json格式 context.JSON(http.StatusOK, gin.H{“status”: 200}) }) r.Run(“:8088”) }

  1. > postman进行测试
  2. > ```json
  3. //request
  4. {
  5. "username":"root",
  6. "password":"admin"
  7. }
  8. //result
  9. {
  10. "status": 200
  11. }

表单数据解析和绑定 Bind()

```go package main

import ( “github.com/gin-gonic/gin” “net/http” )

type Login struct { UserName string form:"username" json:"username" uri:"username" xml:"username" binding:"required" Password string form:"password" json:"password" uri:"password" xml:"password" binding:"required" }

func main() { //创建路由 r := gin.Default() //创建POST请求 r.POST(“/login”, func(context *gin.Context) { var form Login //Bind默认解析并绑定form格式 if err := context.Bind(&login); err != nil { context.JSON(http.StatusBadRequest, gin.H{“error”: err.Error()}) return } if form.UserName != “root” || form.Password != “admin” { context.JSON(http.StatusBadRequest, gin.H{“status”: “304”}) return } //返回json格式 context.JSON(http.StatusOK, gin.H{“status”: 200}) }) r.Run(“:8088”) }

  1. <a name="5d74f98f"></a>
  2. #### URL数据解析和绑定
  3. > ```go
  4. package main
  5. import (
  6. "github.com/gin-gonic/gin"
  7. "net/http"
  8. )
  9. type Login struct {
  10. UserName string `form:"username" json:"username" uri:"username" xml:"username" binding:"required"`
  11. Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
  12. }
  13. func main() {
  14. //创建路由
  15. r := gin.Default()
  16. //创建POST请求
  17. r.POST("/login", func(context *gin.Context) {
  18. var form Login
  19. //ShouldBindUri绑定URL格式
  20. if err := context.ShouldBindUri(&login); err != nil {
  21. context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  22. return
  23. }
  24. if form.UserName != "root" || form.Password != "admin" {
  25. context.JSON(http.StatusBadRequest, gin.H{"status": "304"})
  26. return
  27. }
  28. //返回json格式
  29. context.JSON(http.StatusOK, gin.H{"status": 200})
  30. })
  31. r.Run(":8088")
  32. }

响应格式

  1. c.JSON()//json格式响应
  2. c.XML()//XML格式响应
  3. c.YAML()//YAML格式响应
  4. c.ProtoBuf()//ProtoBuf 谷歌开发的高效存储读取工具

同步异步

goroutine 机制可以方便的实现异步处理。