Swag是一款Golang的API文档生成工具,可以根据代码注释自动生成RESTful API接口文档。集成Swag和net/http库可以简化API文档的编写过程,提高开发效率。
以下是Swag与net/http集成的步骤:
- 安装Swag
使用go get命令安装Swag:
go get -u github.com/swaggo/swag/cmd/swag
- 在项目中添加Swag注释
在代码中添加Swagger注释,例如:
// @Summary 获取用户信息
// @Description 根据用户ID获取用户信息
// @Tags 用户信息
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Success 200 {object} UserResponse
// @Failure 400 {object} ErrorResponse
// @Router /users/{id} [get]
func getUserInfo(w http.ResponseWriter, r *http.Request) {
// ...
}
- 生成Swagger文件
使用Swag命令生成Swagger文件:
swag init --generalInfo=./main.go --output=./docs/swagger/
其中–generalInfo指定了包含Swagger注释的Go文件路径,–output指定了生成的Swagger文件输出路径。
- 集成Swagger UI
将从上一步生成的swagger.json文件放到静态资源目录中,并在HTTP处理程序中添加Swagger UI路由:
package main
import (
"embed"
"github.com/gorilla/mux"
"github.com/swaggo/files"
"github.com/swaggo/http-swagger"
"net/http"
)
//go:embed docs/swagger/*
var staticFiles embed.FS
func main() {
r := mux.NewRouter()
// 静态文件路由
r.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", http.FileServer(http.FS(staticFiles))))
// Swagger UI路由
r.Handle("/docs", httpSwagger.Handler(
httpSwagger.URL("http://localhost:8080/swagger/doc.json"), // Swagger文件URL
httpSwagger.DeepLinking(true),
httpSwagger.DocExpansion("none"),
httpSwagger.DomID("#swagger-ui"),
httpSwagger.ConfigURL("/swagger/ui"),
))
// API路由
r.HandleFunc("/users/{id}", getUserInfo).Methods("GET")
// 启动HTTP服务器
http.ListenAndServe(":8080", r)
}
其中,staticFiles变量包含了从生成的swagger.json文件到静态资源目录中的所有Swagger UI资源。http-swagger库提供了一个方便的Handle函数来处理Swagger UI路由。