如何强制golang将文件链接到我的二进制文件中?

问题描述:

I want to create a module library where a files can be added and will be part of my binary.

For example, in my package main I have:

type InitFunc func(params DriverParams) (Driver, error)

func Register(name string, f InitFunc) {
}

Then I would like someone to add a file in the modules directory that calls Register().

Subsequently my main package will call all the functions that have registered themselves.

This way, my main package has no prior knowledge of the modules that will be added.

How do I accomplish this in golang?

我想创建一个模块库,可以在其中添加文件并将其作为二进制文件的一部分。 p>

例如,在我的包main code>中,我有: p>

  type InitFunc func(params DriverParams)( 驱动程序,错误)
 
func寄存器(名称字符串,f InitFunc){
} 
  code>  pre> 
 
 

然后我希望有人在模块目录中添加文件 调用 Register() code>。 p>

随后,我的主程序包将调用所有已注册自身的函数。 p>

此 方式,我的主软件包对要添加的模块没有先验知识。 p>

我如何在golang中做到这一点? p> div>

In short - you cannot. Go links everything statically and does some optimizations so the module you installing may not even be compiled if you do not reference it explicitly from main. Such limitation makes people suffer and they do this - the plugins are just normal Go applications communicating with the main app via RPC.

It may sound weird (when one part of your app talks to another via TCP stack), but if you think about a bit more then it actually gives you quite strong confidence that plugin will do no harm to the application. For example, when the plugin crashes, the rest of the application, most likely, will survive.