根據指令1.16 or newer
go install github.com/swaggo/swag/cmd/swag@latest
....
確認下載工具成功
$ swag -v
swag version v1.8.6
可以查看對應指令
$ swag init --help
2. 根據gin-swagger說明 ,在main.go路徑 下swag init
see from https://github.com/swaggo/gin-swagger
會產生
swag init
cmd/app-core/docs/docs.go
cmd/app-core/docs/swagger.json
cmd/app-core/docs/swagger.yaml
3. 加入swagger 相關的註解或code
3-1 根據gin-swagger說明 ,在main.go 添加說明
import (
"github.com/gin-gonic/gin"
+ _ "github.com/minilabmemo/go-rest-arch/cmd/app-core/docs"
)
加入註解
+// @title Swagger Example API
+// @version 1.0
+// @description This is a sample server celler server.
func main() {
start := time.Now()
errs := make(chan error, 3)
listenForInterrupt(errs)
startup(errs)
defer stopMain()
zap.S().Infof("Service started in: %v", time.Since(start))
zap.S().Infof("Version %s", internal.Version)
c := <-errs
zap.S().Warnf("terminating: %v", c)
}
或者
import (
+ docs "github.com/minilabmemo/go-rest-arch/cmd/app-core/docs"
)
func main() {
+ docs.SwaggerInfo.Title = fmt.Sprintf("Swagger %s API", config.ConfigData.Service.Name)
}
3-2 在對應HttpServer啟動的地方加入swagger UI的路由
記得在對應的gomod 獲取相關的dependency
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
package apis
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/minilabmemo/go-rest-arch/internal/config"
+ swaggerfiles "github.com/swaggo/files"
+ ginSwagger "github.com/swaggo/gin-swagger"
"go.uber.org/zap"
)
func StartHttpServer(errChan chan error, engine *gin.Engine) {
+ engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
endpoint := fmt.Sprintf(":%d", config.ConfigData.Service.Port)
go func() {
errChan <- engine.Run(endpoint)
}()
zap.S().Infof("Listening on port: %d", config.ConfigData.Service.Port)
}
4. 添加完之後再下一次swag init 啟動go run main.go
打開http://localhost:8888/swagger/index.html 就可以看到對應的swagger UI了
可是這時還沒有任何可以用的API註解
5. 添加對應的API Info路由註解
// @Summary Get info API
// @Schemes
// @Description Get info API
// @Tags infos
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /service/api/v1/info [get]
func (a *InfoHandler) GetInfo(c *gin.Context) {
//call usecase method
info, _ := a.CUsecase.GetInfo()
c.JSON(http.StatusOK, info)
}
添加完再下一次swag init --parseDependency 。
如果讀取的路由在不同dependency下可以這樣去抓到底層的註解
參考範例:go-rest-arch/tree/feat-info-apis
參考: