go-zero 生成 swagger 并上传到 yapi

661 阅读1分钟

goctl-swagger & yapi-cli

1. 安装插件依赖

GOPROXY=https://goproxy.cn/,direct go install github.com/zeromicro/goctl-swagger@latest

npm install -g yapi-cli

2. 配置环境

将 $GOPATH/bin 中的 goctl-swagger 添加到环境变量

3. 使用姿势

3.1 创建 api 文件

info(
 title: "type title here"
 desc: "type desc here"
 author: "type author here"
 email: "type email here"
 version: "type version here"
)

type (
 RegisterReq {
  Username string `json:"username"`
  Password string `json:"password"`
  Mobile string `json:"mobile"`
 }

 LoginReq {
  Username string `json:"username"`
  Password string `json:"password"`
 }

 UserInfoReq {
  Id string `path:"id"`
 }

 UserInfoReply {
  Name string `json:"name"`
  Age int `json:"age"`
  Birthday string `json:"birthday"`
  Description string `json:"description"`
  Tag []string `json:"tag"`
 }

 UserSearchReq {
  KeyWord string `form:"keyWord"`
 }
)

service user-api {
 @doc(
  summary: "注册"
 )
 @handler register
 post /api/user/register (RegisterReq)

 @doc(
  summary: "登录"
 )
 @handler login
 post /api/user/login (LoginReq)

 @doc(
  summary: "获取用户信息"
 )
 @handler getUserInfo
 get /api/user/:id (UserInfoReq) returns (UserInfoReply)

 @doc(
  summary: "用户搜索"
 )
 @handler searchUser
 get /api/user/search (UserSearchReq) returns (UserInfoReply)
}

3.2 生产 swagger.json

一种是直接用命令语句

~~goctl api plugin -plugin goctl-swagger="swagger -filename user.json" -api user.api -dir .~~

另外一种新建 Makefile 文件的方式 ,同时在Makefile 当前目录下,新建 docs/swagger 目录,并且在当前目录新建 yapi-import.json 的文件(推荐,一劳永逸

yapi-import.json

{
  "type": "swagger",
  "token": "xxxxxx",
  "file": "swagger.json",
  "merge": "normal",
  "server": "https://{xxxx.com}/group/{groupid}"
}

这里只需要改 token 值, token 为 yapi项目设置那里的token值

Markfile

swagger:
    goctl api plugin -plugin goctl-swagger="swagger -filename ./docs/swagger/swagger.json" -api checkin.api -dir .

yapi:
    cd ./docs/swagger && yapi import

执行即可