1. swagger簡述
Swagger
是全球最大的OpenAPI
規范(OAS)API開發工具框架,支持從設計和文檔到測試和部署的整個API生命周期的開發。
接口規范swagger2.0(aka openAPI 2.0),https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md。
使用Swagger,就是把相關的API信息存儲在它定義的描述文件里面(yml或json格式),再通過維護這個描述文件可以去更新接口文檔,以及生成各端代碼。
生成yaml或json描述文檔的方法:可以手動編輯(通過swagger-editor或vim等);也可在代碼中增加規則指定的注釋,然后利用工具自動生成json或yaml。
swagger提供的工具:
Swagger Editor: Swagger描述文件的編輯器,支持實時更新。也提供了在線編輯器和本地部署編輯器兩種方式。
Swagger UI:提供了一個可視化的UI頁面展示描述文件,可以在該頁面中對相關接口進行查閱和做一些簡單的接口請求。該項目支持在線導入描述文件和本地部署UI項目。
Swagger Codegen: 通過Codegen 可以將描述文件生成html格式和cwiki形式的接口文檔,同時也能生成多鍾語言的服務端和客戶端的代碼。
Swagger Inspector: 一個可以對接口進行測試的在線版的postman。比在Swagger UI里面做接口請求,會返回更多的信息,也會保存你請求的實際請求參數等數據。
Swagger Hub:集成了上面所有項目的各個功能,你可以以項目和版本為單位,將你的描述文件上傳到Swagger Hub中。在Swagger Hub中可以完成上面項目的所有工作,需要注冊賬號,分免費版和收費版。
2. go-swagger
go build -o swagger cmd/swagger/swagger.go cp swagger ~/go/bin
使用
$ swagger -h Usage: swagger [OPTIONS] <command> Swagger tries to support you as best as possible when building APIs. It aims to represent the contract of your API with a language agnostic description of your application in json or yaml. Application Options: -q, --quiet silence logs --log-output=LOG-FILE redirect logs to file Help Options: -h, --help Show this help message Available commands: diff diff swagger documents expand expand $ref fields in a swagger spec flatten flattens a swagger document generate generate go code init initialize a spec document mixin merge swagger documents serve serve spec and docs validate validate the swagger document version print the version
校驗
swagger validate autodoc.yml
UI server
Usage: swagger [OPTIONS] serve [serve-OPTIONS] serve a spec and swagger or redoc documentation ui Application Options: -q, --quiet silence logs --log-output=LOG-FILE redirect logs to file Help Options: -h, --help Show this help message [serve command options] --base-path= the base path to serve the spec and UI at -F, --flavor=[redoc|swagger] the flavor of docs, can be swagger or redoc (default: redoc) --doc-url= override the url which takes a url query param to render the doc ui --no-open when present won't open the the browser to show the url --no-ui when present, only the swagger spec will be served --flatten when present, flatten the swagger spec before serving it -p, --port= the port to serve this site [$PORT] --host= the interface to serve this site, defaults to 0.0.0.0 [$HOST]
-F=swagger使用 Petstore 托管的 SwaggerUI 打開一個新選項卡。服務器啟用了 CORS,並將標准 JSON 的 URL 作為請求字符串附加到 petstore URL。
-F=redoc將文檔托管在您自己的計算機上(localhost:port/docs)。
-no-open是為了限制客戶端的界面打開(因為多數時候服務都是后台console執行)
swagger serve --host=0.0.0.0 --port=2399 --no-open autodoc.yml
服務端code
swagger generate server [-f ./swagger.json] -A [application-name [--principal [principal-name]]
客戶端code
swagger generate client [-f ./swagger.json] -A [application-name [--principal [principal-name]]
3. gin-swagger
go get github.com/swaggo/swag/cmd/swag
2. 安裝gin-swagger
$ go get -u github.com/swaggo/gin-swagger $ go get -u github.com/swaggo/files
3. 導入gin-swagger
import "github.com/swaggo/gin-swagger" // gin-swagger middleware import "github.com/swaggo/files" // swagger embed files
4. 示例
// main.go
一定要導入 docs,如“demo/docs"。
注:ginSwagger.URL的port必須和本服務端口相同,doc.json位於默認的docs目錄下,本質就是通過GET("/swagger/*any")訪問本地端口下的docs/docs.go文件。
docs/docs.go是對json和yaml的封裝。
package main import ( _ "demo/docs" "github.com/gin-gonic/gin" "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" "net/http" ) func main() { r := gin.Default() r.POST("/login", login) // r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // default: doc.json // r.Run(":8888") // default :8080 // other way url := ginSwagger.URL("http://localhost:8888/swagger/doc.json") // the rul pointing to API r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url)) r.Run(":8888") // default :8080 } // @登錄 // @Description login // @Accept json // @Produce json // @Param username path string true "username" // @Param passwd path string true "passwd" // @Success 200 {string} string "ok" // @Router /login [post] func login(c *gin.Context){ username := c.PostForm("username") passwd := c.PostForm("passwd") c.String(http.StatusOK, "Hello world "+username+"_"+passwd) }
$go mod init demo
5. 生成api文檔
. ├── docs │ ├── docs.go │ ├── swagger.json │ └── swagger.yaml ├── go.mod ├── go.sum └── main.go
注:不同版本swag效果不同,swag@1.7.0時,swag init必須要和main.go在同一目錄,而swag@1.5.0則可以直接遍歷整個目錄下的go文件。
go get -u github.com/swaggo/swag/cmd/swag@v1.5.0
6. 運行
$ go run main.go [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] POST /login --> main.login (3 handlers) [GIN-debug] GET /swagger/*any --> github.com/swaggo/gin-swagger.CustomWrapHandler.func1 (3 handlers) [GIN-debug] Listening and serving HTTP on :8888 [GIN] 2020/04/06 - 20:01:33 | 200 | 392.909µs | ::1 | GET "/swagger/index.html" [GIN] 2020/04/06 - 20:01:34 | 200 | 228.911µs | ::1 | GET "/swagger/swagger-ui.css" [GIN] 2020/04/06 - 20:01:34 | 200 | 819.055µs | ::1 | GET "/swagger/swagger-ui-bundle.js" [GIN] 2020/04/06 - 20:01:34 | 200 | 413.233µs | ::1 | GET "/swagger/swagger-ui-standalone-preset.js" [GIN] 2020/04/06 - 20:01:34 | 200 | 250.205µs | ::1 | GET "/swagger/doc.json" [GIN] 2020/04/06 - 20:01:34 | 200 | 2.352787ms | ::1 | GET "/swagger/favicon-32x32.png"
4. windows安裝swagger editor
git clone https://github.com/swagger-api/swagger-editor.git //從github下載swagger-editor cd swagger-editor //進入到下載的文件夾中 npm install cd .. //回退到上一曾目錄 http-server swagger-editor //啟動swagger-editor
3. 安裝問題
在運行 npm install 命令的時候報錯(npm ERR! errno -4048,Error:EPERM:operation not permitted) ?
用管理員權限打開 DOS窗口,運行npm cache clean --force,再運行 npm install
http-server commond not found ?npm install http-server -g
參考:
2. golang restful 框架之 go-swagger
3. 使用 SwaggerUI 創建 Golang API 文檔