Skip to content

Instantly share code, notes, and snippets.

@dnephin
Created February 4, 2018 19:11
Show Gist options
  • Save dnephin/8b5d131f4ca7019fe8e7d1c3ab4db399 to your computer and use it in GitHub Desktop.
Save dnephin/8b5d131f4ca7019fe8e7d1c3ab4db399 to your computer and use it in GitHub Desktop.
Testing golang plugins with package init()
package main
import (
"fmt"
"github.com/dnephin/ppp/foo"
"plugin"
)
func main() {
fmt.Println("MAIN")
plug, err := plugin.Open("plugin.so")
if err != nil {
panic(err)
}
sym, err := plug.Lookup("Plugin")
if err != nil {
panic(err)
}
foo.Foo()
sym.(func())()
}
package main
import (
"fmt"
"github.com/dnephin/ppp/foo"
)
func main() {
fmt.Println("PLUGIN MAIN")
}
func Plugin() {
fmt.Println("PLUGIN")
foo.Foo()
}
package foo
import "fmt"
func init() {
fmt.Println("RUNNING")
}
func Foo() {
fmt.Println("FOO")
}
# go build --buildmode=plugin ./cmd/plugin/
# go run ./cmd/main/main.go
RUNNING
MAIN
FOO
PLUGIN
FOO
@podocarp
Copy link

podocarp commented Jun 3, 2024

So in summary, the plugin init() will only be called when any symbol from the plugin is loaded. Whereas a regular package's init will occur before any execution has occured at all. Thanks for the testing, this should have been included in the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment