Created
February 4, 2018 19:11
-
-
Save dnephin/8b5d131f4ca7019fe8e7d1c3ab4db399 to your computer and use it in GitHub Desktop.
Testing golang plugins with package init()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/dnephin/ppp/foo" | |
) | |
func main() { | |
fmt.Println("PLUGIN MAIN") | |
} | |
func Plugin() { | |
fmt.Println("PLUGIN") | |
foo.Foo() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo | |
import "fmt" | |
func init() { | |
fmt.Println("RUNNING") | |
} | |
func Foo() { | |
fmt.Println("FOO") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# go build --buildmode=plugin ./cmd/plugin/ | |
# go run ./cmd/main/main.go | |
RUNNING | |
MAIN | |
FOO | |
PLUGIN | |
FOO | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.