gorilla/mux 框架 (rk-boot): 添加 Swagger UI

768 阅读1分钟

介绍

本文将介绍如何在 gorilla/mux 框架之上提供 Swagger UI。

请访问如下地址获取完整 gorilla/mux 教程:

先决条件

gorilla/mux 没有自带生成 Swagger UI 配置文件的功能。

我们需要安装 swag 命令行工具来生成 Swagger UI 配置文件。

安装选项:通过 swag 官网

$ go get -u github.com/swaggo/swag/cmd/swag

安装 rk-boot

我们介绍 rk-boot 库,用户可以快速搭建 gorilla/mux 微服务。

go get github.com/rookie-ninja/rk-boot/mux

快速开始

1.创建 boot.yaml

boot.yaml 文件会告诉 rk-boot 如何启动 gorilla/mux 服务,下面的例子中,我们指定了端口,Swagger UI 的 json 文件路径。

---
mux:
  - name: greeter        # Required
    port: 8080           # Required
    enabled: true        # Required
    sw:
      enabled: true      # Optional, default: false
      jsonPath: "docs"   # Optional, default: ""
#      path: "sw"        # Default value is "sw", change it as needed
#      headers: []       # Headers that will be set while accessing swagger UI main page.

2.创建 main.go

为了能让 swag 命令行生成 Swagger UI 参数文件,我们需要在代码中写注释。

详情可参考 swag 官方文档。

// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.

package main

import (
	"context"
	"fmt"
	"github.com/rookie-ninja/rk-boot"
	"github.com/rookie-ninja/rk-boot/mux"
	"github.com/rookie-ninja/rk-mux/interceptor"
	"net/http"
)

// @title Swagger Example API
// @version 1.0
// @description This is a sample rk-demo server.
// @termsOfService http://swagger.io/terms/

// @securityDefinitions.basic BasicAuth

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
	// Create a new boot instance.
	boot := rkboot.NewBoot()

	// Register handler
	entry := rkbootmux.GetMuxEntry("greeter")
	entry.Router.NewRoute().Methods(http.MethodGet).Path("/v1/greeter").HandlerFunc(Greeter)

	// Bootstrap
	boot.Bootstrap(context.TODO())

	boot.WaitForShutdownSig(context.TODO())
}

// @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(writer http.ResponseWriter, request *http.Request) {
	rkmuxinter.WriteJson(writer, http.StatusOK, &GreeterResponse{
		Message: fmt.Sprintf("Hello %s!", request.URL.Query().Get("name")),
	})
}

// Response.
type GreeterResponse struct {
	Message string
}

3.生成 swagger 参数文件

默认会在 docs 文件夹里面创建三个文件。rk-boot 会使用 swagger.json 来初始化 Swagger UI 界面。

$ swag init

$ tree
.
├── boot.yaml
├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
├── go.mod
├── go.sum
└── main.go

1 directory, 7 files

4.验证

访问:localhost:8080/sw