beego api - swagger doc

1.beego api doc

对于新建项目,使用api文档,可使用以下命令

bee api apiTests  //该方法用于创建带有api-doc的项目,即新建项目
bee run -gendoc=true -downdoc=true
//浏览器测试
http://localhost:s8080/swagger //有时会遇到跨域的问题,使用127.0.0.1
http://127.0.0.1:8080/swagger/

对于已经存在的项目,需要增加swagger-doc,可按以下步骤来:

(1.)修改配置app.conf中

appname = project
httpport = 8080
runmode = dev
autorender = false
copyrequestbody = true
EnableDocs = true  //关键
sqlconn =

(2.)main函数中新增

if beego.BConfig.RunMode == "dev" {
	beego.BConfig.WebConfig.DirectoryIndex = true
	beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}

(3.)router.go中新增
在行首新增

// @APIVersion 1.0.0
// @Title beego Test API
// @Description beego has a very cool tools to autogenerate documents for your API
// @Contact [email protected]
// @TermsOfServiceUrl http://beego.me/
// @License Apache 2.0
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html

修改router.go中init函数,修改为自己的controller对象

ns := beego.NewNamespace("/v1",
		beego.NSNamespace("/object",
			beego.NSInclude(
				&controllers.ObjectController{},
			),
		),
		beego.NSNamespace("/user",
			beego.NSInclude(
				&controllers.UserController{},
			),
		),
	)
	beego.AddNamespace(ns)

(4.)controller类上加注解

// @Title CreateUser
// @Description create users
// @Param	body		body 	models.User	true		"body for user content"
// @Success 200 {int} models.User.Id
// @Failure 403 body is empty
// @router / [post]
func (u *UserController) Post() {
	var user models.User
	json.Unmarshal(u.Ctx.Input.RequestBody, &user)
	uid := models.AddUser(user)
	u.Data["json"] = map[string]string{"uid": uid}
	u.ServeJSON()
}

(5.)执行以下命令:

bee run -gendoc=true -downdoc=true
//测试
http://localhost:s8080/swagger //有时会遇到跨域的问题,使用127.0.0.1
http://127.0.0.1:8080/swagger/

(6.)其他,使用swagger插件

Settings --> Plugins --> Swagger Plugins || Swagger Codegen

即可在本地编写yaml 格式的Swagger配置文件,左边配置,右边可视化。

相关链接

https://beego.me/docs/advantage/docs.md
https://doc.xuwenliang.com/docs/beego_cn/625
https://my.oschina.net/astaxie/blog/284072#h2_2

猜你喜欢

转载自www.cnblogs.com/tomtellyou/p/12613106.html