Skip to content
鼓励作者:欢迎打赏犒劳

swagger文档

安装依赖

shell
# 安装 swag 命令行工具。全局安装的, 它的任务是扫描你的Go代码,解析你写的特殊注释(比如 // @Summary、// @Router),然后生成标准格式的 swagger.json 和 swagger.yaml 文档文件
go install github.com/swaggo/swag/cmd/swag@latest
# swag 命令行工具生成的 docs/docs.go 文件会依赖这个库。简单说,swag 命令行生成代码,而生成的代码引用了这个 swag 库里的类型定义
go get -u github.com/swaggo/swag
# Swagger UI 是一个漂亮的网页界面,用于可视化地展示和测试你的 API。swaggo/files 库将这些前端资源打包成了 Go 代码
go get -u github.com/swaggo/files
#这是一个Hertz 框架的适配器/中间件
go get -u github.com/hertz-contrib/swagger

重要改动

shell

import (
	_ "demo/docs" # 改成你的模块名,例如 _ "xinxiang-system/docs"
)

# 2. 代码里加一行
h.GET("/swagger/*any", swagger.WrapHandler())
# 3. 生成文档
swag init
# 4. 启动
go run main.go
# 5. 访问
open http://localhost:8080/swagger/index.html

完整代码

访问:http://localhost:8080/swagger/index.html

go
package main

import (
	"context"
	_ "demo/docs" // 改成你的模块名,例如 _ "xinxiang-system/docs"
	"strconv"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"github.com/hertz-contrib/swagger"
	swaggerFiles "github.com/swaggo/files"
)

// ========== 这是 Swagger 的全局元信息 ==========

// @title          新乡制造企业管理系统 API
// @version         1.0
// @description     这是新乡制造企业的后端API文档
// @termsOfService  http://swagger.io/terms/

// @contact.name   API Support
// @contact.email  support@xinxiang.com

// @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

// ========== 定义入参/出参结构体 ==========

// CreateOrderRequest 创建订单请求
type CreateOrderRequest struct {
	UserID   int64   `json:"user_id" example:"1001"`        // 用户ID
	Product  string  `json:"product" example:"iPhone 15"`   // 商品名称
	Price    float64 `json:"price" example:"5999.00"`       // 单价
	Quantity int     `json:"quantity" example:"2"`          // 数量
	Remark   string  `json:"remark,omitempty" example:"加急"` // 备注
}

// OrderResponse 创建订单响应
type OrderResponse struct {
	Code    int       `json:"code" example:"200"`
	Message string    `json:"message" example:"订单创建成功"`
	Data    OrderData `json:"data"`
}

// OrderData 订单数据
type OrderData struct {
	OrderID    int64   `json:"order_id" example:"12345"`
	UserID     int64   `json:"user_id" example:"1001"`
	Product    string  `json:"product" example:"iPhone 15"`
	TotalPrice float64 `json:"total_price" example:"11998.00"`
}

// UpdateUserRequest 更新用户请求
type UpdateUserRequest struct {
	ID   int64  `path:"id" example:"100"`  // 用户ID(来自路径)
	Name string `json:"name" example:"张三"` // 姓名
	Age  int    `json:"age" example:"28"`  // 年龄
}

// ========== 业务Handler(带文档注释) ==========

// CreateOrder 创建订单
// @Summary      创建订单
// @Description  创建一个新的订单,包含商品信息和数量
// @Tags         订单管理
// @Accept       json
// @Produce      json
// @Param        request body CreateOrderRequest true "订单信息"
// @Success      200  {object}  OrderResponse  "创建成功"
// @Failure      400  {object}  map[string]interface{}  "参数错误"
// @Router       /order [post]
func CreateOrder(ctx context.Context, c *app.RequestContext) {
	var req CreateOrderRequest
	if err := c.BindAndValidate(&req); err != nil {
		c.JSON(consts.StatusBadRequest, utils.H{
			"code":    400,
			"message": "参数错误: " + err.Error(),
		})
		return
	}

	// 模拟业务逻辑
	total := req.Price * float64(req.Quantity)

	c.JSON(consts.StatusOK, utils.H{
		"code":    200,
		"message": "订单创建成功",
		"data": utils.H{
			"order_id":    12345,
			"user_id":     req.UserID,
			"product":     req.Product,
			"total_price": total,
		},
	})
}

// GetOrder 获取订单详情
// @Summary      获取订单详情
// @Description  根据订单ID获取订单详细信息
// @Tags         订单管理
// @Accept       json
// @Produce      json
// @Param        id   path      int  true  "订单ID"
// @Success      200  {object}  map[string]interface{}  "成功"
// @Failure      404  {object}  map[string]interface{}  "订单不存在"
// @Router       /order/{id} [get]
func GetOrder(ctx context.Context, c *app.RequestContext) {
	id := c.Param("id")
	c.JSON(consts.StatusOK, utils.H{
		"code":    200,
		"message": "获取订单成功",
		"data": utils.H{
			"order_id": id,
			"product":  "iPhone 15",
			"status":   "已发货",
		},
	})
}

// UpdateUser 更新用户信息
// @Summary      更新用户
// @Description  根据用户ID更新用户信息
// @Tags         用户管理
// @Accept       json
// @Produce      json
// @Param        id      path      int                 true  "用户ID"
// @Param        request body      UpdateUserRequest   true  "用户信息"
// @Success      200     {object}  map[string]interface{}  "更新成功"
// @Failure      400     {object}  map[string]interface{}  "参数错误"
// @Router       /user/{id} [put]
func UpdateUser(ctx context.Context, c *app.RequestContext) {
	var req UpdateUserRequest
	if err := c.BindAndValidate(&req); err != nil {
		c.JSON(consts.StatusBadRequest, utils.H{
			"code":    400,
			"message": "参数错误: " + err.Error(),
		})
		return
	}
	req.ID, _ = strconv.ParseInt(c.Param("id"), 10, 64)

	c.JSON(consts.StatusOK, utils.H{
		"code":    200,
		"message": "用户更新成功",
		"data": utils.H{
			"id":   req.ID,
			"name": req.Name,
			"age":  req.Age,
		},
	})
}

// ========== 主函数 ==========

func main() {
	// 添加这行注释,让swag知道入口在这里
	// @host localhost:8080
	// @BasePath /api/v1

	h := server.Default(
		server.WithHostPorts("0.0.0.0:8080"),
	)

	// 路由分组
	api := h.Group("/api/v1")
	{
		api.POST("/order", CreateOrder)
		api.GET("/order/:id", GetOrder)
		api.PUT("/user/:id", UpdateUser)
	}

	// 启用 Swagger UI(一行搞定)
	h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler))

	h.Spin()
}

如有转载或 CV 的请标注本站原文地址