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
相关推荐
读研的武13 小时前
DashGo零基础入门 纯Python的管理系统搭建
开发语言·python
Andy14 小时前
Python基础语法4
开发语言·python
但要及时清醒14 小时前
ArrayList和LinkedList
java·开发语言
码事漫谈14 小时前
C++中的多态:动态多态与静态多态详解
后端
码事漫谈14 小时前
单链表反转:从基础到进阶的完整指南
后端
孚亭14 小时前
Swift添加字体到项目中
开发语言·ios·swift
hweiyu0014 小时前
Go、DevOps运维开发实战(视频教程)
开发语言·golang·运维开发
mm-q291522272914 小时前
Python+Requests零基础系统掌握接口自动化测试
开发语言·python