Load package dynamically

2020-02-24 07:50发布

问题:

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.

回答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.



回答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.



回答3:

There is support for this now as of go 1.8

https://golang.org/pkg/plugin/



回答4:

Just do these,create a codegen that reads the configuration, generates a basic go file with the packages loaded in order and then execute that, compile languages won't nor provide dynamic loading, even dart suffers in a way,simple just read your configuration file then create a temporary file with the necessary codes to load up and communicate with sockets or http



回答5:

I think what you are looking for is the special function init

if you add a

func init() {

}

inside a package it will run it the first time the package is imported. This happens only in the same binary. As other have already said go does not support dynamically loaded libraries.