【go语言开发】swagger安装和使用
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                在Go中使用Swagger需要使用swag工具生成Swagger文档。以下是安装swag工具的步骤以及如何使用它的示例。
- 安装
swag工具: 
go get -u github.com/swaggo/swag/cmd/swag- 确保
$GOPATH/bin已经添加到你的PATH环境变量中,这样你就可以在命令行中直接运行swag命令。 - 在你的Go项目中使用Swagger注释。例如,在你的
main.go文件中: 
package main
 
import (
    "github.com/swaggo/echo-swagger"
    "github.com/swaggo/swag"
    "github.com/labstack/echo/v4"
)
 
// @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
// @BasePath /v2
func main() {
    e := echo.New()
    
    // ... 其他代码 ...
 
    // 为Echo框架生成Swagger文档
    e.GET("/swagger/*", echoSwagger.WrapHandler)
 
    // ... 其他代码 ...
}- 在命令行中运行
swag工具,指定Swagger注释的格式和输出目录: 
swag init这将会在你的项目目录中生成docs文件夹,里面包含了Swagger的docs和json文件。
- 启动你的应用程序,并访问
http://localhost:8080/swagger/index.html来查看Swagger文档界面。 
确保你的Swagger注释是按照swag工具的要求编写的,这样swag init命令才能正确地生成Swagger文档。
评论已关闭