从插件中删除主机的源代码以减小文件大小
我目前正在尝试使用golang的插件系统.我在测试中遇到的一个问题是,插件的文件大小相对较大.
I'm currently experimenting with golang's plugin system. A problem which I experienced in my testings is that the file size of the plugins is relativly big.
加载插件的应用程序将被称为主机".
The application loading the plugin will be referenced as "host".
主机应用程序本身约为50MiB,因为它是一个Web应用程序,应使用插件功能进行扩展.
The host application itself is ~50MiB big since it is a web application and should be extended with plugin functionality.
我已经实现了一个小型插件加载器来启动插件.
I've implemented a small plugin loader to start the plugins up.
例如,插件可以使用应用程序中已经存在的API来访问数据库.
The plugins may use the already existing APIs in the application for example to access the database.
我已经为这个问题准备了一个示例插件.插件.so文件大小为〜39MiB.这使我有一个合理的怀疑,即该插件还包含来自主机应用程序的源代码.
I've prepared a example plugin for this question. The plugin .so file size is ~39MiB. This gives me the reasonable suspicion that the plugin also contains source code from the host application.
用于创建main.so
的命令:
go build -ldflags="-s -w" --buildmode=plugin main.go
是否可以从应用程序中删除"重复的源代码以减小文件大小,因为在加载插件时已在运行时将其加载?
Is it possible to "remove" the duplicated source code from the application to reduce file size since it is already loaded on runtime when the plugin gets loaded?
插件加载程序: https://github. com/jonasfranz/gitea/blob/feature/plugin/modules/plugins/loader.go
示例插件: https://git.jonasfranz.software/JonasFranzDEV/giteaplugin
源代码未包含在插件中.但是其中包括的是它们的依赖项,递归.之所以这样,是因为不能保证加载插件的主应用程序也包含依赖项,因此,为了确保插件的生存能力,其依赖项必须是自包含的.
Source code is not included in plugins. But what is included in them is their dependencies, recursively. This is so because there is no guarantee that the main app that loads the plugin also contains the dependencies, so to ensure the viability of the plugin, its dependencies must be self-contained.
如果主应用程序还包含相同的依赖项(具有相同的版本),这不会引起问题,它们只会在go运行时中实例化"一次,有关详细信息,请参见Go插件依赖项如何工作?
This does not cause problems if the main app also include the same dependencies (with the same version), they will only be "instantiated" once in the go runtime, for details, see How do Go plugin dependencies work?
该怎么做才能减小插件的大小?除了删除调试信息(您做了什么)之外,您还应该使依赖性最小化.
What to do in order to reduce plugins' sizes? Besides removing the debug information (what you did), you should minimize the dependencies.
这可能需要在插件或您要为其创建插件的应用程序中进行重新设计和重大更改.例如,插件不应引用实现"程序包,插件应仅引用接口"程序包.如果没有将接口和实现分开,那么这可能是不可能的(因此也可能需要更改主应用程序).
This may require redesign and major changes both in the plugin or in the app you wish to create the plugin for. For example, plugins should not refer to "implementation" packages, plugins should only refer to "interface" packages. If interfaces and implementations are not separated, this may not be possible (hence may it be required to change the main app too).
您还可以尝试尝试压缩二进制文件的实用程序,有关详细信息,请参见:
You may also try utilities that try to compress binaries, for details see: Shrink your Go binaries with this one weird trick