英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论