go-swagger标准接口暴露

添加依赖

复制代码
	github.com/gin-gonic/gin v1.11.0
	github.com/swaggo/files v1.0.1
	github.com/swaggo/gin-swagger v1.6.1
	github.com/swaggo/swag v1.16.6

定义返回值

复制代码
package response

type ResultVO struct {
	Code    int         `json:"code"`              //错误码
	Message string      `json:"message,omitempty"` //错误信息
	Data    interface{} `json:"data,omitempty"`    //返回的数据
}

type UserVO struct {
	ID    int    `json:"id"`    // ID
	Name  string `json:"name"`  // 用户姓名
	Email string `json:"email"` // 邮箱
}

定义参数

复制代码
package param

type UserParam struct {
	ID    int    `json:"id"`    // ID
	Name  string `json:"name"`  // 用户姓名
	Email string `json:"email"` // 邮箱
}

创建controller

复制代码
package controller

import (
	"github.com/gin-gonic/gin"
)

type UserController struct {
}

func NewUserController() *UserController {
	return &UserController{}
}

// @Summary 获取用户信息
// @Description 获取用户详细信息
// @Accept json
// @Produce json
// @Param id query int64 true "用户id"
// @Success 200 {object} response.ResultVO{data=response.UserVO}
// @Router /user/get [get]
func (u *UserController) GetUser(c *gin.Context) {

}

// @Summary 添加用户信息
// @Description 添加用户信息
// @Accept json
// @Produce json
// @Param user body param.UserParam true "用户信息"
// @Success 200 {object} response.ResultVO{data=response.UserVO}
// @Router /user/add [post]
func (u *UserController) AddUser(c *gin.Context) {

}

// @Summary 分页获取用户信息
// @Description 分页获取用户信息
// @Accept json
// @Produce json
// @Param pageSize query int64 true "一页几条"
// @Param current query int64 true "当前页"
// @Success 200 {object} response.ResultVO{data=[]response.UserVO}
// @Router /user/list [get]
func (u *UserController) ListUser(c *gin.Context) {

}

初始化swagger文件

复制代码
swag init

启动服务

复制代码
package main

import (
	"swagger_test/controller"
	_ "swagger_test/docs" //之前使用swag init 生成的swagger文档的路径

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func main() {
	r := gin.Default()
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	userController := controller.NewUserController()
	r.GET("/user/get", userController.GetUser)
	r.POST("/user/add", userController.AddUser)
	r.GET("/user/list", userController.ListUser)
	r.Run(":8080")
}

访问接口

复制代码
http://127.0.0.1:8080/swagger/index.html#/default
相关推荐
小强1988几秒前
MySQL到底用不用JOIN?——从执行计划、数据量、分库分表角度分析最佳实践
后端
NQBJT几秒前
VS Code配置Python人工智能开发环境
开发语言·人工智能·vscode·python
fliter7 分钟前
现在可以用纯 Rust 写 Cloudflare Workers 了,不需要一行 JavaScript
后端
byoass8 分钟前
智巢AI知识库深度解析:企业文档管理从大海捞针到精准狙击的进化之路
开发语言·网络·人工智能·安全·c#·云计算
掘金一周18 分钟前
你们觉得房贷多少,没有压力 | 沸点周刊 4.30
前端·人工智能·后端
南境十里·墨染春水19 分钟前
C++笔记 STL——set
开发语言·c++·笔记
L16247620 分钟前
Win11 共享→Windows Server 访问故障总结(极简可复用)
开发语言·windows·php
oldking呐呐1 小时前
MySQL从建库到删库跑路 -- 4.表的操作
后端·mysql
渐儿1 小时前
I/O 多路复用与 Reactor 模式:高性能服务的根基
后端
.柒宇.1 小时前
FastAPI 基础指南:从入门到实战
开发语言·python·fastapi