现在大部分应用都是前后端分离的项目,那么,前端和后端交互只有通过api接口文档来实现。swagger可以根据注释来生成api接口文档。
go get github.com/swaggo/swag/cmd/swag
go get github.com/gin-gonic/gin
go get github.com/go-sql-driver/mysql
go get gorm.io/gorm
go get gorm.io/gorm/logger
go get github.com/swaggo/gin-swagger
go get github.com/swaggo/files
此时会在环境变量 GOBIN 目录中生成swag.exe
model.go
package main
import "github.com/jinzhu/gorm"
type Post struct {
gorm.Model
Title string `gorm:"type:varchar(100);" josn:"title" example:"title" binding:"required"`
Des string `gorm:"type:varchar(100);" josn:"des" example:"desc" binding:"required"`
Status string `gorm:"type:varchar(200);" josn:"status" example:"Active"`
}
type Response struct {
Msg string
Data interface{
}
}
api.go
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
//查询
func Posts(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
var posts []Post
db.Limit(limit).Offset(offset).Find(&posts)
c.JSON(http.StatusOK, gin.H{
"messege": "",
"data": posts,
})
}
func Show(c *gin.Context) {
post := getById(c)
c.JSON(http.StatusOK, gin.H{
"messege": "",
"data": post,
})
}
func Store(c *gin.Context) {
var post Post
if err := c.ShouldBindJSON(&post); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"messege": err.Error(<