如何在多个插件上分配路由

How to distribute routes over several plugins

我目前正在从事一个项目,该项目需要将 HTTP 路由分布在多个插件上。目前使用的是 fiber 框架,如果需要可以切换到另一个框架。 该项目的结构如下:

+ base
|
+-- main
|    | base-routes.go
|
+--plugins
|    |
|    + Plugin1
|    | plugin1-routes.go
|    | further files omitted
|    | 
|    + Plugin2
|    | plugin2-routes.go
|    |

是否有机会根据安装的插件动态添加路由? 在调用 go run base.go --plugins=plugin1 之后,所有路由并且只有这些路由被添加到主路由中,这将是完美的。在调用 go run base.go --plugins=plugin1,plugin2 时应建立所有路由。

使用 Fiber 和其他 Web 框架,如 Echo、Gin 等,您可以仅使用 if 语句有条件地添加路由。

Fiber 中的初始化如下所示 (https://github.com/gofiber/fiber#%EF%B8%8F-quickstart):

    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World !")
    })

有条件逻辑:

package main

import (
    "flag"
    "github.com/gofiber/fiber/v2"
)

func main() {

    cliflags := flag.String("plugins", "", "")
    flag.Parse()

    app := fiber.New()

    // verify not nil or something else according to your flag pattern
    if cliflags != nil {
        app.Get("/", func(c *fiber.Ctx) error {
            return c.SendString("Hello, World !")
        })
    }

    app.Listen(":3000")
}