作者采用Beego框架主要是用来做后端接口的服务,swagger大家应该知道是一款优秀的自动化Api生成文档的工具,可用于提供接口测试,参数显示。帮助开发者进行快速的接口开发。

    1.配置文件开启应用内的文档
    Beego整合swagger自动化文档的搭建 - 图1
    2.打开Terminal终端采用命令
    bee run -gendoc=true -downdoc=true
    自动从github下载swagger.zip压缩包并解压 在项目当中会出现一个swagger文件夹
    下载报错的话 则重新下载
    文件夹下面会出现 swagger文件夹查看swagger文件夹则表示下载成功
    Beego整合swagger自动化文档的搭建 - 图2

    swagger全局注释在router.go的package上面声明
    编写接口

    1. package controllers
    2. import "github.com/astaxie/beego"
    3. // hello Api
    4. type HelloWorld struct {
    5. beego.Controller
    6. }
    7. func (this*HelloWorld)UrlMapping(){
    8. this.Mapping("GetHello",this.GetHello)
    9. }
    10. // @Title GetHello
    11. // @Description get all the staticblock by key
    12. // @Param key path string true "The email for login"
    13. // @Success 200 {object} models.ZDTCustomer.Customer
    14. // @Failure 400 Invalid email supplied
    15. // @Failure 404 User not found
    16. // @router /GetHello
    17. func (this *HelloWorld)GetHello(){
    18. this.Data["json"]="HelloWorld"
    19. //输出json格式
    20. this.ServeJSON()
    21. }

    应用开启自动化文档

    1. package main
    2. import (
    3. _ "test/routers"
    4. "github.com/astaxie/beego"
    5. )
    6. func main() {
    7. beego.BConfig.WebConfig.DirectoryIndex = true
    8. beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
    9. beego.Run()
    10. }
    1. // @APIVersion 1.0.0
    2. // @Title first API
    3. // @Description HelloWorld Api
    4. // @Contact 3285198650@qq.com
    5. package routers
    6. import (
    7. "test/controllers"
    8. "github.com/astaxie/beego"
    9. )
    10. func init() {
    11. beego.Router("/", &controllers.MainController{})
    12. //配置路由
    13. namespace := beego.NewNamespace("v1",
    14. beego.NSNamespace("hello",
    15. beego.NSInclude(
    16. &controllers.HelloWorld{},
    17. ),
    18. ),
    19. )
    20. beego.AddNamespace(namespace)
    21. }

    采用bee run -gendoc=true 运行
    浏览器访问:http://localhost:8080/swagger 出现如下图表示swagger文档整合成功
    Beego整合swagger自动化文档的搭建 - 图3