go集成gin+swagger

go集成gin+swagger,第1张

go集成gin+swagger 1.安装 swag
go get github.com/swaggo/swag/cmd/swag
swag 用于生成 docs 文件夹(swagger文档程序使用)

安装完成后会在 ${GOPATH}/bin生成一个执行文件

2.编写代码

package main

import (
	_ "lys_gin_swag/docs"

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

// @title lys_gin_swag微服务api
// @version 0.0.1
// @description  lys_gin_swag微服务 code  by 刘云生
// @basePath /
func main() {
	r := gin.New()

	// 创建路由组
	v1 := r.Group("/api/v1")

	v1.GET("/sayHello/:name", sayHello)

	v2 := r.Group("/api/v2")

	v2.GET("/sayHello/:name", sayHello2)

	// 文档界面访问URL
	// http://127.0.0.1:8080/swagger/index.html
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	r.Run(":8080")
}

// @sayHello
// @Description sayHello
// @Accept  json
// @Produce json
// @Param   name     path    string     true        "name"
// @Success 200 {string} string	"name,helloWorld"
// @Router /api/v1/sayHello/{name} [get]
func sayHello(c *gin.Context) {
	name := c.Param("name")

	c.JSON(200, gin.H{
		"describe": "this is /api/v1 ",
		"name":     name,
	})
}

// @sayHello2
// @Description sayHello2
// @Accept  json
// @Produce json
// @Param   name     path    string     true        "name"
// @Success 200 {string} string	"name,helloWorld"
// @Router /api/v2/sayHello/{name} [get]
func sayHello2(c *gin.Context) {
	name := c.Param("name")

	c.JSON(200, gin.H{
		"describe": "this is /api/v2",
		"action":   name,
	})
}

3.swag init

执行 swag init


4.运行效果

go run main.go

进入 http://127.0.0.1:8080/swagger/index.html 查看文档

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5708701.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存