代码改变世界

golang 生成swagger 文档

2023-02-18 16:50  糯米粥  阅读(148)  评论(0编辑  收藏  举报

 

github:

https://github.com/swaggo/swag/blob/master/README_zh-CN.md

 

参考:https://www.cnblogs.com/cxykhaos/p/15345317.html

 

第一步:下载swag

命令:go install github.com/swaggo/swag/cmd/swag@latest

 

通过swag -v 查看命令

 

 

 

通过swag init 生成文档

 

 

 

 

 

项目结构:

 

 

 

controller -》 user.go
package controller

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
    "swagger/model"
)

// @Summary 用户服务 (摘要)
// @Description 用户服务2
// @Tags 用户服务
// @Accept mpfd
// @Produce json
// @Param Id query int true "用户id"
// @Success        200    {object}        model.User
// @Failure 400 {string} string "{"msg": "who are you"}"
// @Router /GetUserById [get]
func GetUserById(c *gin.Context) {
    userId, _ := strconv.Atoi(c.Query("Id"))
    c.JSON(http.StatusOK, gin.H{
        "code": 200,
        "msg":  "success",
        "data": model.User{
            Id:       userId,
            UserName: "tom",
            Mobile:   "15888888888",
        },
    })
    return
}
View Code

 

 model -> user.go

package model

import "github.com/gofrs/uuid"

type User struct {
    Id       int    /*主键*/
    UserName string //用户名
    Mobile   string //手机号码
    UUID     uuid.UUID
}
View Code

 

main.go

要引入doc

 

 

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/swaggo/files"
    "github.com/swaggo/gin-swagger"
    "swagger/controller"
    _ "swagger/docs"
)

// gin-swagger middleware
// swagger embed files

// @title           Swagger Example API
// @version         1.0
// @description     This is a sample server celler 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      localhost:8080
// @BasePath  /api/v1

// @securityDefinitions.basic  BasicAuth
func main() {
    /////////////
    r := gin.Default()
    //c := controller.NewController()
    v1 := r.Group("/api/v1")
    {
        v1.GET("/GetUserById", controller.GetUserById)
        //accounts := v1.Group("/accounts")
        //{
        //    //accounts.GET(":id", controller.HandleHello)
        //    accounts.GET("/GetUserById", controller.GetUserById)
        //    //accounts.GET("", c.ListAccounts)
        //    //accounts.POST("", c.AddAccount)
        //    //accounts.DELETE(":id", c.DeleteAccount)
        //    //accounts.PATCH(":id", c.UpdateAccount)
        //    //accounts.POST(":id/images", c.UploadAccountImage)
        //}
        //...
    }
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    r.Run(":8080")
}
View Code