This is a general question about Go Plugin initialization.
I want to make a certain package in a Go program to a Go Plugin.
The package (say mypackage
) has a variable which is initialized with a function call from a certain package in the executable. (E.g. a variable of type interface Logger
which is to be initialized by a logger.CreateLogger
function.)
In order to make mypackage
a plugin, I need to create a main
package, embed mypackage
inside main
, and export an api Init
in package main
which accepts a function which can get me a logger.
I want to do this so as to reduce the dependencies of my plugin. The mypackage
plugin should depend on the interface Logger
rather than Logger's implementation.
Now the problem is the initialization, in the case of executable, the initialization could have happened as below:
package mypackage
var dlog = logger.CreateLogger("mypackage")
And the logger can be used in any func init()
function of mypackage
.
After converting to a plugin, it can't be initialized like this. It has to be initialized at a later point after the main.Init
is invoked.
The func init
is invoked when the plugin is Opened, so it cannot be used to initialize variables.
Only solution seems to be a creating a function per package, and invoke it from an exported function in main
package.
package mypackage
var dlog Logger
func Init(f createLoggerType){
dlog = f()
yetanotherpackage.Init(f)
}
package main
func Init(f createLoogerType) {
mypackage.Init(f)
anotherpackage.Init(f)
}
Is there a better way to initialize? I tried checking github.com/facebookgo/inject
but couldn't figure out how it can be used in case of plugins.