Swagger是一個面向開發者的API框架,用於設計、構建、文檔化和消費RESTful Web服務,其功能強大,被廣泛應用在Web開發中。本文將介紹如何使用Golang實現Swagger接口文檔。
一、編寫Golang代碼
首先,我們需要先編寫Golang代碼實現Web服務。在本例中,我們使用`go-chi/chi`包來構建RESTful路由。以下是一個簡單的`main.go`文件,它將監聽端口`8080`,並響應GET請求。
“`go
package main
import (
“net/http”
“github.com/go-chi/chi”
)
func main() {
r := chi.NewRouter()
r.Get(“/”, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(“Hello World!”))
})
http.ListenAndServe(“:8080”, r)
}
“`
二、添加Swagger文檔支持
要使用Swagger,我們需要使用一個Swagger庫,如`go-swagger/go-swagger`。我們還需要通過注釋定義API的請求和響應,將其轉換為Swagger規範。以下是我們更新後的`main.go`文件。
“`go
package main
import (
“net/http”
“github.com/go-chi/chi”
“github.com/go-chi/chi/middleware”
“github.com/go-chi/docgen”
“github.com/go-chi/render”
“github.com/swaggo/http-swagger”
“github.com/swaggo/swag”
)
// @title My API
// @version 1.0
// @description This is a sample API
// @host localhost:8080
// @BasePath /
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(render.SetContentType(render.ContentTypeJSON))
r.Get(“/”, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(“Hello World!”))
})
r.Get(“/swagger/*”, httpSwagger.Handler(
httpSwagger.URL(“http://localhost:8080/swagger/doc.json”), //The url pointing to API definition”
))
// swagger:route GET /users users listUsers
//
// Lists all users.
//
// This will show all available users.
//
// Consumes:
// – application/json
//
// Produces:
// – application/json
//
// Schemes: http, https, ws, wss
//
// Responses:
// 200: usersResponse
r.Get(“/users”, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{“message”: “This shows all available users.”}`))
})
// swagger:response usersResponse
type usersResponse struct {
//in:body
Body struct {
// message of the response
Message string `json:”message”`
} `json:”body”`
}
// Generate Swagger specification
swaggerSpec := swag.New(
swag.WithBasePath(“”),
swag.WithTitle(“My API”),
swag.WithVersion(“1.0”),
swag.WithDescription(“This is a sample API”),
)
// Generate Swagger JSON
swaggerJSON, _ := docgen.JSONRoutesDoc(r)
swaggerSpec = json.RawMessage(swaggerJSON)
// Serve Swagger JSON
r.Get(“/swagger/doc.json”, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(“Content-Type”, “application/json”)
w.Write(swaggerJSON)
})
http.ListenAndServe(“:8080”, r)
}
“`
在此代碼中,我們引入了以下包:
– `github.com/go-chi/middleware`:中間件支持。
– `github.com/go-chi/docgen`:生成Swagger規範。
– `github.com/swaggo/http-swagger`:Swagger UI。
我們使用Swagger注釋說明接口的請求和響應規範,如上例所示。
使用`swag.New`方法生成Swagger規範,再使用`docgen.JSONRoutesDoc`方法生成Swagger JSON。
最後,我們添加一個路由,用於返回Swagger JSON。這個路由將在瀏覽器中訪問`http://localhost:8080/swagger/index.html`時使用。
三、運行應用程序
在本例中,我們可以通過運行以下命令來運行應用程序:
“`bash
go run .
“`
現在,我們可以在瀏覽器中訪問`http://localhost:8080/swagger/index.html`來查看API的Swagger文檔。
四、總結
在本文中,我們學習了如何使用Golang實現Swagger接口文檔。我們編寫了一個簡單的Golang Web服務,並使用Swagger庫和注釋添加了API規範。這使得我們可以使用Swagger UI輕鬆地瀏覽我們的API。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/270261.html