Load package dynamically
Solution 1
You might consider executing the ‘plugin’ packages at runtime, by writing out a new program (say, to a temp directory) and executing via exec.Command, something along the lines of exec.Command("go", "run", files…).Run()
You’ll see some similar code here.
Solution 2
No, Go doesn't support dynamically loaded libraries.
Your best bet is to start the plugin as its own executable and communicate with it through sockets or via stdin/stdout.
2017 update
This answer is no longer true, Go now supports plugins (for Linux and MacOS only as of June 2021)
Solution 3
There is support for this now as of go 1.8
https://golang.org/pkg/plugin/
Related videos on Youtube
Pepeluis
Updated on July 09, 2022Comments
-
Pepeluis almost 2 years
Is it possible to load a specific package during runtime? I want to have a kind of plugins where each one has the same functions than the others but with different behaviour, and depending on the configuration file, load one or other.
-
Pepeluis almost 10 yearsBut in that way, how can I load the package for the first time without knowing which package would be used?
-
Pepeluis almost 10 yearsHi, thank you, it could solve my problem, and I could communicate both with zeroMQ or similar.
-
Pepeluis almost 10 yearsThe problem with init is that I don't know which package should be loaded until the config file is read. So if I can't load a package dynamically, the init way is not the solution.
-
zhaozhi over 9 yearsI make "dynamic loading" by build several plugins independently, these plugins must support reading data from stdin, then in the main.go, I read plugin list from a config file, then use exec.Command to start each plugin (in go routine), then I can write to plugins' StdinPipe, and each plugin can read.
-
Petar about 9 years"compile languages won't nor provide dynamic loading" - c/c++ are compiled languages and they do provide it through 'dlopen'. Virtually all languages provide some sort of dynamic loading except for go.
-
Mikhail T. almost 8 yearsAnd now there is a dlopen-package for Go, which allows use of shared libraries. How you generate those -- and whether you can turn Go-code into a library -- are separate concerns...
-
user2679859 about 7 yearsBut still only on Linux (as of go 1.8)
-
OneOfOne about 7 yearsWell, linux and osx.
-
Aaron over 6 yearsIt's not stable yet!
The plugin support is currently incomplete, only supports Linux, and has known bugs. Please report any issues.