beego的API自動化文檔

2023-11-21 10:46 更新

API自動化文檔

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

API 全局設置

必須設置在 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

全局的注釋如上所示,是顯示給全局應用的設置信息,有如下這些設置

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

路由解析須知

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

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

應用注釋

接下來就是我們最重要的注釋了,就是我們定義的,我們先來看一個例子:

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 定義上面的注釋,這個是用來顯示這個模塊的作用。接下來就是每一個函數(shù)上面的注釋,這里列出來支持的各種注釋:

  • @Title

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

  • @Description

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

  • @Param

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

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

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

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

  • @Failure

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

  • @router

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

如何自動化生成文檔

要使得文檔工作,你需要做幾個事情,

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

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

可能遇到的問題

  1. CORS 兩種解決方案:

    • 把 swagger 集成到應用中,下載請到swagger,然后放在項目目錄下:

        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. 未知錯誤,因為這是我自己項目中使用的,所以可能大家在寫的過程中會遇到一些莫名的錯誤,請?zhí)?issue 去吧!


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號