要在Debian上部署Swagger文档,你需要先安装一个Go语言环境,因为Swagger文档是通过Go语言编写的。以下是详细的步骤:
sudo apt update
sudo apt install golang
go version
go install github.com/swaggo/swag/cmd/swag@latest
go get -u github.com/gin-gonic/gin
go get -u github.com/swaggo/files
go get -u github.com/swaggo/gin-swagger
mkdir myapp
cd myapp
mkdir docs
main.go
文件中添加Swagger注释,例如:package main
import (
"github.com/gin-gonic/gin"
"myapp/docs" // 引入docs包,以便swag自动生成文档
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"net/http"
)
// @title Swagger Example API
// @version 1.0
// @description 这是一个简单的API文档示例
// @termsOfService http://swagger.io/terms/
// @contact.name api support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @host localhost:8080
// @basePath /api/v1
func main() {
r := gin.Default()
// 设置Swagger文档的路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// 注册API路由
api := r.Group("/api/v1")
api.GET("/hello", helloworld)
// 启动服务
r.Run(":8080")
}
// @summary 说你好
// @description 输出一个问候信息
// @tags hello
// @accept json
// @produce json
// @success 200 {string} string "success"
// @router /hello [get]
func helloworld(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hello, world!"})
}
在项目根目录下运行以下命令生成Swagger文档:
swag init
go run main.go
http://localhost:8080/swagger/index.html
,即可查看自动生成的Swagger文档。以上步骤完成后,你就可以在Debian上成功部署Swagger文档了。