Post

beego 高级编程

beego 高级编程

进程内监控

API 自动化文档

API 全局设置

必须设置在 routers/router.go 文件的注释,最顶部:

1
2
3
4
5
  // @APIVersion 1.0.0
  // @Title mobile API
  // @Description mobile has every tool to get any job done, so codename for the new mobile APIs.
  // @Contact astaxie@gmail.com
  package routers

全局的注释如上所示,是显示给全局应用的设置信息,有如下这些设置

  • @APIVersion
  • @Title
  • @Description
  • @Contact
  • @TermsOfServiceUrl
  • @License
  • @LicenseUrl

路由解析须知

目前自动化文档只支持如下的写法的解析,其他写法函数不会自动解析,即 namespace+Include 的写法,而且只支持二级解析,一级版本号,二级分别表示应用模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  func init() {
      ns :=
          beego.NewNamespace("/v1",
              beego.NSNamespace("/customer",
                  beego.NSInclude(
                      &controllers.CustomerController{},
                      &controllers.CustomerCookieCheckerController{},
                  ),
              ),
              beego.NSNamespace("/catalog",
                  beego.NSInclude(
                      &controllers.CatalogController{},
                  ),
              ),
              beego.NSNamespace("/newsletter",
                  beego.NSInclude(
                      &controllers.NewsLetterController{},
                  ),
              ),
              beego.NSNamespace("/cms",
                  beego.NSInclude(
                      &controllers.CMSController{},
                  ),
              ),
              beego.NSNamespace("/suggest",
                  beego.NSInclude(
                      &controllers.SearchController{},
                  ),
              ),
          )
      beego.AddNamespace(ns)
  }

应用注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  package controllers

  import "github.com/astaxie/beego"

  // CMS API
  type CMSController struct {
      beego.Controller
  }

  func (c *CMSController) URLMapping() {
      c.Mapping("StaticBlock", c.StaticBlock)
      c.Mapping("Product", c.Product)
  }

  // @Title getStaticBlock
  // @Description get all the staticblock by key
  // @Param   key     path    string  true        "The email for login"
  // @Success 200 {object} models.ZDTCustomer.Customer
  // @Failure 400 Invalid email supplied
  // @Failure 404 User not found
  // @router /staticblock/:key [get]
  func (c *CMSController) StaticBlock() {

  }

  // @Title Get Product list
  // @Description Get Product list by some info
  // @Success 200 {object} models.ZDTProduct.ProductList
  // @Param   category_id     query   int false       "category id"
  // @Param   brand_id    query   int false       "brand id"
  // @Param   query   query   string  false       "query of search"
  // @Param   segment query   string  false       "segment"
  // @Param   sort    query   string  false       "sort option"
  // @Param   dir     query   string  false       "direction asc or desc"
  // @Param   offset  query   int     false       "offset"
  // @Param   limit   query   int     false       "count limit"
  // @Param   price           query   float       false       "price"
  // @Param   special_price   query   bool        false       "whether this is special price"
  // @Param   size            query   string      false       "size filter"
  // @Param   color           query   string      false       "color filter"
  // @Param   format          query   bool        false       "choose return format"
  // @Failure 400 no enough input
  // @Failure 500 get products common error
  // @router /products [get]
  func (c *CMSController) Product() {

  }

Other

首先是 CMSController 定义上面的注释,这个是用来显示这个模块的作用。接下来就是每一个函数上面的注释,这里列出来支持的各种注释:

@Title

这个 API 所表达的含义,是一个文本,空格之后的内容全部解析为 title

@Description

这个 API 详细的描述,是一个文本,空格之后的内容全部解析为 Description

@Param

参数,表示需要传递到服务器端的参数,有五列参数,使用空格或者 tab 分割,五个分别表示的含义如下

参数名 参数类型,可以有的值是 formData、query、path、body、header,formData 表示是 post 请求的数据,query 表示带在 url 之后的参数,path 表示请求路径上得参数,例如上面例子里面的 key,body 表示是一个 raw 数据请求,header 表示带在 header 信息中得参数。 参数类型 是否必须 注释

@Success

成功返回给客户端的信息,三个参数,第一个是 status code。第二个参数是返回的类型,必须使用 {} 包含,第三个是返回的对象或者字符串信息,如果是 {object} 类型,那么 bee 工具在生成 docs 的时候会扫描对应的对象,这里填写的是想对你项目的目录名和对象,例如 models.ZDTProduct.ProductList 就表示 /models/ZDTProduct 目录下的 ProductList 对象。

三个参数必须通过空格分隔

@Failure

失败返回的信息,包含两个参数,使用空格分隔,第一个表示 status code,第二个表示错误信息

@router

路由信息,包含两个参数,使用空格分隔,第一个是请求的路由地址,支持正则和自定义路由,和之前的路由规则一样,第二个参数是支持的请求方法,放在 [] 之中,如果有多个方法,那么使用 , 分隔。

自动化生成文档

  • 第一开启应用内文档开关,在配置文件中设置:EnableDocs = true
  • 然后在你的 main.go 函数中引入 _ “beeapi/docs”(beego 1.7.0 之后版本不需要添加该引用)
  • 这样你就已经内置了 docs 在你的 API 应用中,然后你就使用 bee run -gendoc=true -downdoc=true,让我们的 API 应用跑起来,-gendoc=true 表示每次自动化的 build 文档,-downdoc=true 就会自动的下载 swagger 文档查看器

备注

CORS 两种解决方案:

把 swagger 集成到应用中,下载请到 swagger,然后放在项目目录下:

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

API 增加 CORS 支持

1
ctx.Output.Header("Access-Control-Allow-Origin", "*")

自动生成代码

1
2
3
4
5
6
bee generate appcode -tables="news" -conn="root:123123@tcp(127.0.0.1:3306)/beegodb"

bee generate appcode -tables="cargo_track" -conn="root:zhly@2019@tcp(47.244.225.92:9936)/yun_mao?charset=utf8&loc=Asia%2FShanghai"


bee generate scaffold goods -fields="id:int,name:string,image:string" -conn="root:123123@tcp(127.0.0.1:3306)/beegodb"
This post is licensed under CC BY 4.0 by the author.