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

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

How do I force golang to link a file into my binary?

问题

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

例如,在我的package main中,我有:

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

func Register(name string, f InitFunc) {
}

然后,我希望有人在模块目录中添加一个调用Register()的文件。

随后,我的主包将调用所有已注册的函数。

这样,我的主包不需要事先知道将要添加的模块。

在Go语言中,我该如何实现这一点?

英文:

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?

答案1

得分: 4

简而言之,你无法直接在Go中动态链接模块。Go会将所有内容静态链接并进行一些优化,因此如果你没有在主程序中显式引用该模块,它甚至可能不会被编译。这种限制使人们感到困扰,所以他们采用了这种方法 - 插件只是通过RPC与主应用程序进行通信的普通Go应用程序。

这听起来可能有些奇怪(当应用程序的一部分通过TCP堆栈与另一部分通信),但如果你再仔细考虑一下,实际上它给你带来了相当强大的信心,即插件不会对应用程序造成任何伤害。例如,当插件崩溃时,应用程序的其余部分很可能会继续运行。

英文:

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.

huangapple
  • 本文由 发表于 2015年7月30日 05:02:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/31711068.html
匿名

发表评论

匿名网友

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

确定