Gin-Swagger中time.Time类型处理及默认参数设置问题
解决方案
一、让gin-swagger正确识别并处理time.Time类型
gin-swagger原生支持time.Time类型,只需通过结构体标签指定格式,就能让生成的OpenAPI文档将其识别为date-time类型,同时保证gin自动解析为time.Time、gorm正常接收:
- 在Book结构体的
Published字段上添加swagger:"format:date-time"标签,配合gorm的字段类型设置:
import ( "time" "gorm.io/gorm" ) type Book struct { gorm.Model Title string `json:"title" gorm:"size:255"` Published time.Time `json:"published" gorm:"type:datetime" swagger:"format:date-time"` }
- 接口中使用gin的
ShouldBindJSON等绑定方法,它会自动将符合ISO8601格式的时间字符串(如2023-10-05T14:48:00Z)解析为time.Time类型,无需额外处理。
二、为Book结构体设置默认参数示例
如果需要给字段添加示例值,有两种常用实现方式:
方式1:通过结构体标签指定示例
直接在字段的swagger标签中追加example属性:
type Book struct { gorm.Model Title string `json:"title" gorm:"size:255" swagger:"example:Go编程入门"` Published time.Time `json:"published" gorm:"type:datetime" swagger:"format:date-time,example:2023-10-05T14:48:00Z"` }
方式2:在API注释中指定示例
在接口的swagger注释里,通过@Param的example参数直接定义请求体的完整示例:
// @Summary 创建书籍 // @Accept json // @Produce json // @Param book body Book true "书籍信息" example({"title":"Go编程入门","published":"2023-10-05T14:48:00Z"}) // @Success 200 {object} Book // @Router /books [post] func CreateBook(c *gin.Context) { var book Book if err := c.ShouldBindJSON(&book); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } db.Create(&book) c.JSON(http.StatusOK, book) }
这样生成的Swagger文档中,Published字段会被正确识别为date-time类型,同时显示预设的示例值,方便前端测试对接。
内容的提问来源于stack exchange,提问作者Mohamad-Jaafar NEHME
相关产品推荐
相关产品推荐

