beego的API自動(dòng)化文檔

2023-11-21 10:46 更新

API自動(dòng)化文檔

自動(dòng)化文檔一直是我夢(mèng)想中的一個(gè)功能,這次借著公司的項(xiàng)目終于實(shí)現(xiàn)了出來(lái),我說(shuō)過(guò) beego 不僅僅要讓開發(fā) API 快,而且讓使用 API 的用戶也能快速的使用我們開發(fā)的 API,這個(gè)就是我開發(fā)這個(gè)項(xiàng)目的初衷。好了,趕緊動(dòng)手實(shí)踐一把吧,首先 bee api beeapi 新建一個(gè) API 應(yīng)用做起來(lái)吧。

API 全局設(shè)置

必須設(shè)置在 routers/router.go 中,文件的注釋,最頂部:

// @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

全局的注釋如上所示,是顯示給全局應(yīng)用的設(shè)置信息,有如下這些設(shè)置

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

路由解析須知

目前自動(dòng)化文檔只支持如下的寫法的解析,其他寫法函數(shù)不會(huì)自動(dòng)解析,即 namespace+Include 的寫法,而且只支持二級(jí)解析,一級(jí)版本號(hào),二級(jí)分別表示應(yīng)用模塊

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)
}

應(yīng)用注釋

接下來(lái)就是我們最重要的注釋了,就是我們定義的,我們先來(lái)看一個(gè)例子:

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() {

}

首先是 CMSController 定義上面的注釋,這個(gè)是用來(lái)顯示這個(gè)模塊的作用。接下來(lái)就是每一個(gè)函數(shù)上面的注釋,這里列出來(lái)支持的各種注釋:

  • @Title

    這個(gè) API 所表達(dá)的含義,是一個(gè)文本,空格之后的內(nèi)容全部解析為 title

  • @Description

    這個(gè) API 詳細(xì)的描述,是一個(gè)文本,空格之后的內(nèi)容全部解析為 Description

  • @Param

    參數(shù),表示需要傳遞到服務(wù)器端的參數(shù),有五列參數(shù),使用空格或者 tab 分割,五個(gè)分別表示的含義如下

    1. 參數(shù)名
    2. 參數(shù)類型,可以有的值是 formData、query、path、body、header,formData 表示是 post 請(qǐng)求的數(shù)據(jù),query 表示帶在 url 之后的參數(shù),path 表示請(qǐng)求路徑上得參數(shù),例如上面例子里面的 key,body 表示是一個(gè) raw 數(shù)據(jù)請(qǐng)求,header 表示帶在 header 信息中得參數(shù)。
    3. 參數(shù)類型
    4. 是否必須
    5. 注釋
  • @Success

    成功返回給客戶端的信息,三個(gè)參數(shù),第一個(gè)是 status code。第二個(gè)參數(shù)是返回的類型,必須使用 {} 包含,第三個(gè)是返回的對(duì)象或者字符串信息,如果是 {object} 類型,那么 bee 工具在生成 docs 的時(shí)候會(huì)掃描對(duì)應(yīng)的對(duì)象,這里填寫的是想對(duì)你項(xiàng)目的目錄名和對(duì)象,例如 models.ZDTProduct.ProductList 就表示 /models/ZDTProduct 目錄下的 ProductList 對(duì)象。

    三個(gè)參數(shù)必須通過(guò)空格分隔

  • @Failure

    失敗返回的信息,包含兩個(gè)參數(shù),使用空格分隔,第一個(gè)表示 status code,第二個(gè)表示錯(cuò)誤信息

  • @router

    路由信息,包含兩個(gè)參數(shù),使用空格分隔,第一個(gè)是請(qǐng)求的路由地址,支持正則和自定義路由,和之前的路由規(guī)則一樣,第二個(gè)參數(shù)是支持的請(qǐng)求方法,放在 [] 之中,如果有多個(gè)方法,那么使用 , 分隔。

如何自動(dòng)化生成文檔

要使得文檔工作,你需要做幾個(gè)事情,

  • 第一開啟應(yīng)用內(nèi)文檔開關(guān),在配置文件中設(shè)置:EnableDocs = true,
  • 然后在你的 main.go 函數(shù)中引入 _ "beeapi/docs"(beego 1.7.0 之后版本不需要添加該引用)。
  • 這樣你就已經(jīng)內(nèi)置了 docs 在你的 API 應(yīng)用中,然后你就使用 bee run -gendoc=true -downdoc=true,讓我們的 API 應(yīng)用跑起來(lái),-gendoc=true 表示每次自動(dòng)化的 build 文檔,-downdoc=true 就會(huì)自動(dòng)的下載 swagger 文檔查看器

好了,現(xiàn)在打開你的瀏覽器查看一下效果,是不是已經(jīng)完美了。下面是我的 API 文檔效果:

可能遇到的問(wèn)題

  1. CORS 兩種解決方案:

    • 把 swagger 集成到應(yīng)用中,下載請(qǐng)到swagger,然后放在項(xiàng)目目錄下:

        if beego.BConfig.RunMode == "dev" {
            beego.BConfig.WebConfig.DirectoryIndex = true
            beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
        }
      
    • API 增加 CORS 支持

        ctx.Output.Header("Access-Control-Allow-Origin", "*")
      
  2. 未知錯(cuò)誤,因?yàn)檫@是我自己項(xiàng)目中使用的,所以可能大家在寫的過(guò)程中會(huì)遇到一些莫名的錯(cuò)誤,請(qǐng)?zhí)?issue 去吧!


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)