/
use_plugin_example.go
50 lines (42 loc) · 1.03 KB
/
use_plugin_example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"fmt"
"log"
"os"
"plugin"
)
type GoodDoctor interface {
HealthCheck() error
}
func init() {
log.Println("main package init function called")
}
func main() {
log.Println("main function stared")
// load module 插件你也可以使用go http.Request从远程下载到本地,在加载做到动态的执行不同的功能
// 1. open the so file to load the symbols
plug, err := plugin.Open("./plugin_doctor.so")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
log.Println("plugin opened")
// 2. look up a symbol (an exported function or variable)
// in this case, variable Doctor
doc, err := plug.Lookup("Doctor")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// 3. Assert that loaded symbol is of a desired type
// in this case interface type GoodDoctor (defined above)
doctor, ok := doc.(GoodDoctor)
if !ok {
fmt.Println("unexpected type from module symbol")
os.Exit(1)
}
// 4. use the module
if err := doctor.HealthCheck(); err != nil {
log.Println("use plugin doctor failed, ", err)
}
}