Load package dynamically

34,469

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/

Share:
34,469

Related videos on Youtube

Pepeluis
Author by

Pepeluis

Updated on July 09, 2022

Comments

  • Pepeluis
    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
    Pepeluis almost 10 years
    But in that way, how can I load the package for the first time without knowing which package would be used?
  • Pepeluis
    Pepeluis almost 10 years
    Hi, thank you, it could solve my problem, and I could communicate both with zeroMQ or similar.
  • Pepeluis
    Pepeluis almost 10 years
    The 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
    zhaozhi over 9 years
    I 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
    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.
    Mikhail T. almost 8 years
    And 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
    user2679859 about 7 years
    But still only on Linux (as of go 1.8)
  • OneOfOne
    OneOfOne about 7 years
    Well, linux and osx.
  • Aaron
    Aaron over 6 years
    It's not stable yet! The plugin support is currently incomplete, only supports Linux, and has known bugs. Please report any issues.