如何在多个插件之间分配路由

huangapple go评论95阅读模式
英文:

How to distribute routes over several plugins

问题

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

+ base
|
+-- main
|    | base-routes.go
|
+--plugins
|    |
|    + Plugin1
|    | plugin1-routes.go
|    | 其他文件省略
|    | 
|    + Plugin2
|    | plugin2-routes.go
|

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

英文:

I am currently working on a project which requires HTTP-Routes being distributed over several plugins. Currently fiber is the used framework, a switch to another framework is possible if need be.
The project is structured like this:

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

Is there a chance of dynamically adding the routes depending on the installed plugins?
It would be perfect that after calling go run base.go --plugins=plugin1 all the routes and only these routes are added to the main routes. On calling go run base.go --plugins=plugin1,plugin2 all the routes should be established.

答案1

得分: 1

使用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()

    // 根据你的标志模式验证非空或其他条件
    if cliflags != nil {
        app.Get("/", func(c *fiber.Ctx) error {
            return c.SendString("Hello, World 👋!")
        })
    }

    app.Listen(":3000")
}
英文:

With Fiber and with other web frameworks as Echo, Gin, ... you can add routes conditionally just with if statements.

Initialization in Fiber looks like this (https://github.com/gofiber/fiber#%EF%B8%8F-quickstart):

    app := fiber.New()

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

With conditional logic:

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")
}

huangapple
  • 本文由 发表于 2021年11月8日 00:24:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/69874327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定