Reputation: 4912
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.
Upvotes: 3
Views: 756
Reputation: 418435
There is nothing wrong with your solution, but if you want to be able to use it in variable declarations and package init()
functions, this is how you can do it. I also think it's easier to use the plugin this way, but this requires a common, shared package between your main app and the plugin.
One option would be to create a "store" package, which could store factory functions or pre-created loggers.
Let's say the Logger
interface definition is in mylogger
:
package mylogger
type Logger interface { Log(string) }
The store
for example:
package store
import "mylogger"
var LoggerFactory func(string) mylogger.Logger
And in your main app initialize it before you load / open the mypackage
plugin:
package main
import "store"
func main() {
store.LoggerFactory = logger.CreateLogger
// Now proceed to load / open mypackage plugin
}
Then the mypackage
plugin may look like this:
package mypackage
import "store"
var dlog = store.LoggerFactory("mypackage")
Upvotes: 1