Load package dynamically

2020-02-24 07:05发布

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.

5条回答
闹够了就滚
2楼-- · 2020-02-24 07:44

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.

查看更多
来,给爷笑一个
3楼-- · 2020-02-24 07:49

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

查看更多
Animai°情兽
4楼-- · 2020-02-24 07:49

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.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-02-24 07:56

There is support for this now as of go 1.8

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

查看更多
做个烂人
6楼-- · 2020-02-24 07:58

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.

查看更多
登录 后发表回答