95 lines
2.1 KiB
Go
Raw Permalink Normal View History

2022-03-08 22:09:04 +08:00
package main
import (
"time"
"github.com/gin-gonic/gin"
_ "github.com/swaggo/gin-swagger/example/basic/docs"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io:8080
// @BasePath /v2
func main() {
r := gin.New()
r.GET("/v2/object", GetObjects)
r.GET("/v2/object/:id", GetAnObject)
r.POST("/v2/object", CreateObject)
_ = r.Run(":8080")
}
type Object struct {
// 这是一个ID
ID int `json:"id"`
// 这是对象的名字
Name string `json:"name"`
}
// APIError example
type APIError struct {
ErrorCode int
ErrorMessage string
CreatedAt time.Time
}
// @Summary get an object
// @Description blabla...
// @Accept json
// @Produce json
// @Param id path int true "Some ID"
// @Success 200 {object} Object "ok"
// @Failure 400 {object} APIError "We need ID!!"
// @Failure 404 {object} APIError "Can not find ID"
// @Router /v2/object [get]
func GetAnObject(c *gin.Context) {
c.JSON(200, Object{
ID: 1,
Name: "hello",
})
}
// @Summary create an object.
// @Description blabla...
// @Accept json
// @Produce json
// @Success 200 {object} Object "ok"
// @Param object body Object true "Add Object"
// @Failure 400 {object} APIError "We need ID!!"
// @Failure 404 {object} APIError "Can not find ID"
// @Router /v2/object [post]
func CreateObject(c *gin.Context) {
c.JSON(200, Object{
ID: 1,
Name: "hello",
})
}
// @Description get struct array by ID
// @Accept json
// @Produce json
// @Param offset query int true "Offset"
// @Param limit query int true "Offset"
// @Success 200 {string} string "ok"
// @Failure 400 {object} APIError "We need ID!!"
// @Failure 404 {object} APIError "Can not find ID"
// @Router /v2/object/{id} [get]
func GetObjects(c *gin.Context) {
c.JSON(200, []Object{
{ID: 1, Name: "hello"},
{ID: 2, Name: "hello"},
})
}