introduce
This article shows you how to provide the Swagger UI on top of the Echo framework.
Please visit the following address for the full Echo tutorial:
- rkdocs.netlify.app/cn
A prerequisite for
Echo has no built-in Swagger UI configuration file generation capability.
We need to install the Swag command-line tool to generate the Swagger UI configuration file.
Installation option 1: via the RK command line
# Install RK CMD
$ go get -u github.com/rookie-ninja/rk/cmd/rk
# Install swag with rk
$ rk install swag
Copy the code
Install option 2: Via the SWAG website
$ go get -u github.com/swaggo/swag/cmd/swag
Copy the code
Install fairly rk – the boot
We introduce the RK-Boot library, which enables users to quickly build micro-services based on the Echo framework.
- The document
- The source code
- example
go get github.com/rookie-ninja/rk-boot
Copy the code
Quick start
1. Create the boot. Yaml
The boot.yaml file tells RK-boot how to start the Echo service. In the following example, we specify the json file path for the port, Swagger UI.
---
echo:
- name: greeter
port: 8080
enabled: true
sw:
enabled: true
jsonPath: "docs"
# path: "sw" # Default value is "sw", change it as needed
# headers: [] # Headers that will be set while accessing swagger UI main page.
Copy the code
2. Create a main. Go
To enable the Swag command line to generate the Swagger UI parameter file, we need to comment it in our code.
Refer to the official SWAG documentation for details.
package main
import (
"context"
"fmt"
"github.com/labstack/echo/v4"
"github.com/rookie-ninja/rk-boot"
"net/http"
)
// @title RK Swagger for Echo
/ / @ version 1.0
// @description This is a greeter service with rk-boot.
func main(a) {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Register handler
boot.GetEchoEntry("greeter").Echo.GET("/v1/greeter", Greeter)
// Bootstrap
boot.Bootstrap(context.Background())
// Wait for shutdown sig
boot.WaitForShutdownSig(context.Background())
}
// @Summary Greeter service
// @Id 1
/ / @ version 1.0
// @produce application/json
// @Param name query string true "Input name"
// @Success 200 {object} GreeterResponse
// @Router /v1/greeter [get]
func Greeter(ctx echo.Context) error {
return ctx.JSON(http.StatusOK, &GreeterResponse{
Message: fmt.Sprintf("Hello %s!", ctx.QueryParam("name")),})}// Response.
type GreeterResponse struct {
Message string
}
Copy the code
3. Generate swagger parameter files
By default, three files are created in the docs folder. Rk-boot initializes the Swagger UI interface with swagger. Json.
$ swag init
$ tree. ├ ─ ─ the boot. Yaml ├ ─ ─ docs │ ├ ─ ─ docs. Go │ ├ ─ ─ swagger. Json │ └ ─ ─ swagger. Yaml ├ ─ ─. Mod ├ ─ ─. Sum └ ─ ─ main. Go 1 directory, 7 filesCopy the code
4. Verify
Access: localhost: 8080 / sw