【问题标题】:Golang auto-including extensible applicationGolang 自动包含可扩展应用程序
【发布时间】:2014-06-10 01:55:35
【问题描述】:

我对 Go 还很陌生,我很好奇是否存在可扩展应用程序的既定设计模式。

例如,在我的源代码中,我有一个扩展目录,我在其中为我的程序放置了不同的应用程序特定扩展。我目前按名称分别在我的主函数中加载每个。我想让程序在编译时自动包含我的扩展。

为了清楚起见,我并不想在运行时动态加载扩展。我只想为程序添加一个扩展,如下所示:

  1. 将文件拖放到扩展文件夹中
  2. 重新编译

如果 Go 无法做到这一点,那么我会尽力而为,但我只是认为必须有更好的方法来做到这一点。

为了更清楚地展示我想要简化的内容,以下是我现在所做的示例:

main.go

package main

import (
    "github.com/go-martini/martini"
    "gopath/project/extensions"
)

func main() {
    app := martini.Classic()

    // Enable Each Extension
    app.Router.Group("/example", extensions.Example)
 // app.Router.Group("/example2", extensions.Example2)
 // ...


    app.Run()
}

extensions/example.go

package extensions

import (
    "github.com/codegangsta/martini-contrib/render"
    "github.com/go-martini/martini"
)

func Example(router martini.Router) {
    router.Get("", func(r render.Render) {
        // respond to query
        r.JSON(200, "")
    })
}

【问题讨论】:

  • 将包放在模块路径的子目录下,然后将子模块导入主模块。但是您需要为所有“扩展”添加一个标准包名称并处理名称冲突等......一场噩梦:D
  • 另一种方法是像 Packer 一样使用 RPC:packer.io/docs/extend/developing-plugins.html

标签: design-patterns go


【解决方案1】:

在每个扩展的 go 文件中使用 init 方法来注册扩展。

所以在plugin1.go 你会写

func init() {
    App.Router.Group("/example", extensions.Example)
}

您需要公开app

您可以在主代码中使用注册函数。

我在rcloneHere is the registration functionhere is an example of it being called 中使用了这种技术。每个模块都编译在by including them in the main pacakge

【讨论】:

  • 谢谢你!我完全忘记了 Go 包中存在 init()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多