1. 结构体验证

用gin框架的数据验证,可以不用解析数据,减少if else,会简洁许多。

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. )
  7. //Person ..
  8. type Person struct {
  9. //不能为空并且大于10
  10. Age int `form:"age" binding:"required,gt=10"`
  11. Name string `form:"name" binding:"required"`
  12. Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
  13. }
  14. func main() {
  15. r := gin.Default()
  16. r.GET("/5lmh", func(c *gin.Context) {
  17. var person Person
  18. if err := c.ShouldBind(&person); err != nil {
  19. c.String(500, fmt.Sprint(err))
  20. return
  21. }
  22. c.String(200, fmt.Sprintf("%#v", person))
  23. })
  24. r.Run()
  25. }

演示地址:

http://localhost:8080/5lmh?age=11&name=枯藤&birthday=2006-01-02