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/n/270261.html