案例包括json、表单和URI三种类型的数据

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. // 定义接收数据的结构体
  7. type Login struct {
  8. User string `form:"username" json:"username" uri:"username" xml:"username" binding:"required"`
  9. Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
  10. }
  11. func main() {
  12. r := gin.Default()
  13. // json
  14. r.POST("/loginJSON", func(c *gin.Context) {
  15. var json Login
  16. if err := c.ShouldBindJSON(&json); err != nil {
  17. // 返回错误信息
  18. // gin.H封装了生成json数据的工具
  19. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  20. return
  21. }
  22. if json.User != "username" || json.Password != "password" {
  23. c.JSON(http.StatusBadRequest, gin.H{"status": "304"})
  24. return
  25. }
  26. c.JSON(http.StatusOK, gin.H{"status": "200"})
  27. })
  28. // form
  29. r.POST("/loginForm", func(c *gin.Context) {
  30. var form Login
  31. // Bind默认解析并绑定form格式
  32. // 根据请求头中content-type自动推断
  33. if err :=c.Bind(&form); err != nil {
  34. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  35. return
  36. }
  37. if form.User != "username" || form.Password != "password" {
  38. c.JSON(http.StatusBadRequest, gin.H{"status": "304"})
  39. return
  40. }
  41. c.JSON(http.StatusOK, gin.H{"status": "200"})
  42. })
  43. // uri
  44. r.POST("/loginUri/:username/:password", func(c *gin.Context) {
  45. var login Login
  46. if err :=c.ShouldBindUri(&login); err != nil {
  47. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  48. return
  49. }
  50. if login.User != "username" || login.Password != "password" {
  51. c.JSON(http.StatusBadRequest, gin.H{"status": "304"})
  52. return
  53. }
  54. c.JSON(http.StatusOK, gin.H{"status": "200"})
  55. })
  56. r.Run()
  57. }