golang學習筆記7 使用beego swagger 實現API自動化文檔


golang學習筆記7 使用beego swagger 實現API自動化文檔

API 自動化文檔 - beego: 簡約 & 強大並存的 Go 應用框架
https://beego.me/docs/advantage/docs.md

使用beego開發api server 和前端拆分開發,使用swagger自動化生成API文檔

Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。 
項目地址是:http://swagger.io/ 
使用 beego 開發自帶集成了 swagger的東西。 
https://beego.me/docs/advantage/docs.md 
github 地址: 
https://github.com/beego/swagger 

到項目目錄下執行命令:
bee run -gendoc=true -downdoc=true
會自動下載最新的 swagger 壓縮文件
啟動成功,直接訪問
http://localhost:8080/swagger/
會出來兩個url,http://localhost:8080/swagger/swagger.json
http://localhost:8080/swagger/swagger.yml

  • 第一開啟應用內文檔開關,在配置文件中設置: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 文檔查看器

https://github.com/swagger-api/swagger-ui 下載zip包,
解壓后把dist文件夾復制到swagger目錄下即可訪問里面的index.html
為了方便把文件夾改名成show,把index.html 的url改成本地的
//url: "http://petstore.swagger.io/v2/swagger.json",
url:"http://localhost:8080/swagger/swagger.json",
在瀏覽器訪問
http://localhost:8080/swagger/show/index.html
即可看到自己項目的api文檔了,示例如下:

 

 

 

 注:如果直接在文件夾打開dist下的index會報跨域的錯誤

 

注:bee pack時swagger 的他會自動解壓文件到swagger目錄下,不需要自己再放個目錄了,可以把之前的show目錄刪掉了

添加auth token的方法,需要改造swagger的index.html

網上很多方法都是行不通的,在下面這個才找到可行的方法

Add JWT authorization header in Swagger v3 · Issue #2915 · swagger-api/swagger-ui · GitHub
https://github.com/swagger-api/swagger-ui/issues/2915

head 里面添加meta(這個swagger實際可以不要,其他測試可用):

<meta name="Authorization" id="head_auth" content="" >

body里面的部分內容改成下面代碼,主要是添加一個configs配置,直接設置在head里面是沒用的,需要設置在SwaggerUIBundle對象里面才有用,最終execute過去的請求是curl:

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
    url: "swagger.json",
    dom_id: '#swagger-ui',
	configs: {
        preFetch: function(req) {
                if (authToken) {
                	req.headers["Authorization"] = authToken;
                }
                return req;
        }
    },
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })

  window.ui = ui
}

var authToken = "";
function addApiKeyAuthorization(){
    var key = encodeURIComponent(document.getElementById('input_apiKey').value);
	authToken = "Bearer " + key;
	//設置請求報文頭
	//var c1 = $("#head_auth").attr('content');
	//console.log("c1 " + c1);
	$("#head_auth").attr('content',authToken);
  }

</script>

  

 

 沒有設置的時候 驗證不通過返回400錯誤信息

 

 

跨域的問題,可以在入口main方法里面加個過濾器filter,允許所有請求都跨域

beego/cors.go at master · astaxie/beego · GitHub
https://github.com/astaxie/beego/blob/master/plugins/cors/cors.go#L23

// Package cors provides handlers to enable CORS support.
// Usage
//	import (
// 		"github.com/astaxie/beego"
//		"github.com/astaxie/beego/plugins/cors"
// )
//
//	func main() {
//		// CORS for https://foo.* origins, allowing:
//		// - PUT and PATCH methods
//		// - Origin header
//		// - Credentials share
//		beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
//			AllowOrigins:     []string{"https://*.foo.com"},
//			AllowMethods:     []string{"PUT", "PATCH"},
//			AllowHeaders:     []string{"Origin"},
//			ExposeHeaders:    []string{"Content-Length"},
//			AllowCredentials: true,
//		}))
//		beego.Run()
//	}

  

或者單個 API 增加 CORS 支持
c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

另外https的無法訪問http的,這個是協議限制的

要方便測試可以把所有都設置成通配符*

beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"*"},
		AllowHeaders:     []string{"*"},
		ExposeHeaders:    []string{"*"},
		AllowCredentials: true,
	}))

  

---------------------------

 QQ群:golang beego技術交流群(316397059)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM