Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money
introduce
This article describes how to provide the Swagger UI on top of the Gin framework.
Please visit the following address for the full Gin tutorial:
- rkdocs.netlify.app/cn
A prerequisite for
Gin does not come with the ability to generate Swagger UI profiles.
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 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 allows users to quickly build microservices based on the Gin 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 Gin service. In the following example, we specify the json file path for the port, Swagger UI.
---
gin:
- 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/gin-gonic/gin"
"github.com/rookie-ninja/rk-boot"
"net/http"
)
// @title RK Swagger for Gin
/ / @ 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.GetGinEntry("greeter").Router.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 *gin.Context) {
ctx.JSON(http.StatusOK, &GreeterResponse{
Message: fmt.Sprintf("Hello %s!", ctx.Query("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. The yaml ├ ─ ─ docs │ ├ ─ ─ docs. Go │ ├ ─ ─ swagger. Json │ └ ─ ─ swagger. Yaml ├ ─ ─. Mod ├ ─ ─. Sum └─ main.go 1 directory, 7 filesCopy the code
4. Verify
Access: localhost: 8080 / sw