Go的“插件系统”

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

"Plugin system" for Go

问题

我正在寻找Go语言的Architect的等价物。

使用Architect,模块可以暴露“插件”。插件可以指定依赖关系,并导出一个API以允许与其他插件进行交互。要启动一个应用程序实例,您需要指定一系列插件。依赖关系将被解析,并按顺序加载(实例化)插件。

由于每个应用程序只创建每个插件的一个实例,因此可以在同一个进程中启动多个应用程序而不会发生冲突。

**编辑:**我不需要其他模块以动态方式加载。

英文:

I'm looking for an equivalent of Architect for the Go language.

With Architect, modules expose "plugins". Plugins can specify dependencies, and export an API to allow interaction with other plugins. To start an application instance, you specify a list of plugins. Dependencies are resolved, and plugins are loaded (instantiated) in order.

Since each application creates a single instance of each plugin, multiple applications can be started in the same process without colliding.

Edit: I don't need the other modules to be loaded dynamically.

答案1

得分: 3

我不知道有一个可以做到这一点的软件包,但是我对如何实现这个功能有一些想法,希望能对你有所帮助。

  • 使用一个构建标签来标识每个插件。
  • 每个插件(文件)在一个特殊的注释/变量中指定它的依赖关系。
  • 运行一个预构建步骤来生成初始化顺序(拓扑排序,在循环中失败)。输出是一个Go文件,其中包含插件系统初始化调用的函数。
  • 使用RegistryPlugin接口,可能是这样的:
type Registry interface {
    // Register registers a plugin under name
    Register(name string, plugin *Plugin) error
    // Get plugin by name
    Get(name string) (*Plugin, error)
}

// 全局注册表
var GlobalRegistry Registry

type Plugin interface {
    // Init 在插件初始化时调用。按依赖顺序执行
    Init(reg Registry) error
    // 执行插件命令
    Exec(name string, args... interface{}) (interface{}, error)
}
  • 运行go build -tags plugin1,plugin2

英文:

I don't of a package that does that, but have some thoughts on how to do that - hope it'll help.

  • Use a build tag for each plugin.

  • Have each plugin (file) specify in a special comment/variable its dependencies

  • Run a pre build step that generate order of initialization (toplogical sort, fail on cycles). The output is a go file which is the function called by the plugin system initialization.

  • Have Registry and Plugin interfaces, probably something like:

      type Registry {
      	// Register registers a plugin under name
      	Register(name string, plugin *Plugin) error
      	// Get plugin by name
      	Get(name string) (*Plugin, error)
      }
    
      // Global Registry
      var GlobalRegistry Registry
    
      type Plugin interface {
      	// Init is called upon plugin initialization. Will be in dependency order
      	Init(reg Registry) error
      	// Execute plugin command
      	Exec(name string, args... interface{}) (interface{}, error)
      }
    
  • Run go build -tags plugin1,plugin2

    1: http://golang.org/pkg/go/build/ "build tags"
    2: http://en.wikipedia.org/wiki/Topological_sorting

huangapple
  • 本文由 发表于 2014年7月19日 19:27:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/24839893.html
匿名

发表评论

匿名网友

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

确定