github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/21_plugin/use/main.go (about)

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