使用OpenAPI文件描述Go應用程式的API並在應用程式中以Swagger UI呈現的方式如下。
在「Golang 使用swaggo產生Swagger REST API文件」是利用swaggo/swag套件產生Go應用程式的REST API文件的Swagger UI頁面;本篇則以OpenAPI文件為Swagger UI的來源。
範例環境:
- Go 1.17
建立Go Web專案
參考「Golang 建立網頁伺服器」建立一個Web專案,並把GET|/hello的handler提取出為HelloHandler()函式。
main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", HelloHandler)
http.ListenAndServe(":8080", nil)
}
func HelloHandler(rw http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
content := fmt.Sprintf("hello, %s", name)
fmt.Fprint(rw, content)
}
下載Swagger UI
在專案根目錄新增swaggerui資料夾,然後下載swagger-ui專案並把dist目錄中的內容複製到專案根目錄下的swaggerui目錄。
建立OpenAPI文件
在swaggerui目錄新增openapi.yaml內容如下:
openapi.yaml
openapi: 3.0.0
info:
contact:
name: "菜鳥工程師肉豬"
url: "https://matthung0807.blogspot.com/"
title: "OpenAPI Demo"
description: OpenAPI.
version: "1.0.0"
servers:
- url: http://localhost:8080
description: local
paths:
"/hello":
get:
parameters:
- in: query
name: name
schema:
type: string
responses:
"200":
description: OK
content:
text/plain:
schema:
type: string
tags:
- Hello
修改swaggerui/index.html中SwaggerUIBundle參數url的值為"./openapi.yaml"。
設定Swagger UI hanlder
設定Swagger UI的路徑為GET|/swagger,handler為http.FileServer()導向檔案系統目錄swaggerui的內容。
main.go
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", HelloHandler)
fs := http.FileServer(http.Dir("./swaggerui")) // Swagger UI files handler
http.Handle("/swagger/", http.StripPrefix("/swagger/", fs))
http.ListenAndServe(":8080", nil)
}
func HelloHandler(rw http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
content := fmt.Sprintf("hello, %s", name)
fmt.Fprint(rw, content)
}
開啟Swagger UI頁面
啟動專案並在瀏覽器輸入http://localhost:8080/swagger進入Swagger UI REST API頁面如下。
沒有留言:
張貼留言