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
- 測試
- 用戶