Gin允许我们自定义参数验证器,[参考1](https://github.com/gin-gonic/gin/blob/master/examples/custom-validation/server.go),[参考2](https://github.com/go-playground/validator/releases/tag/v8.7),[参考3](https://github.com/gin-gonic/gin/tree/master/examples/struct-lvl-validations)
```
package main
import (
"net/http"
"reflect"
"time"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"gopkg.in/go-playground/validator.v8"
)
// Booking contains binded and validated data.
type Booking struct {
CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
}
func bookableDate(
v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
) bool {
if date, ok := field.Interface().(time.Time); ok {
today := time.Now()
if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
return false
}
}
return true
}
func main() {
route := gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("bookabledate", bookableDate)
}
route.GET("/bookable", getBookable)
route.Run(":8085")
}
func getBookable(c *gin.Context) {
var b Booking
if err := c.ShouldBindWith(&b, binding.Query); err == nil {
c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
```
```
$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
{"message":"Booking dates are valid!"}
$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}
```
- 简介
- 安装
- 快速入门
- 代码示例
- 使用 GET, POST, PUT, PATCH, DELETE, OPTIONS
- 获取路径中的参数
- 获取Get参数
- 获取Post参数
- Get + Post 混合
- 上传文件
- 路由分组
- 无中间件启动
- 使用中间件
- 写日志文件
- 自定义日志格式
- 模型绑定和验证
- 自定义验证器
- 只绑定Get参数
- 绑定Get参数或者Post参数
- 绑定uri
- 绑定HTML复选框
- 绑定Post参数
- XML、JSON、YAML和ProtoBuf 渲染(输出格式)
- 设置静态文件路径
- 返回第三方获取的数据
- HTML渲染
- 多个模板文件
- 重定向
- 自定义中间件
- 使用BasicAuth()(验证)中间件
- 中间件中使用Goroutines
- 自定义HTTP配置
- 支持Let's Encrypt证书
- Gin运行多个服务
- 优雅重启或停止
- 构建包含模板的二进制文件
- 使用自定义结构绑定表单数据
- 将请求体绑定到不同的结构体中
- HTTP/2 服务器推送
- 自定义路由日志的格式
- 设置并获取cookie
- 测试
- 用户