好像手上有场景可以用Go1.8的插件来弄,写了个例子.
plug3/plug3.go:
package main
/*
封装Key到.so
Author: XCL
Date: 2017-7-16
*/
type ApiKey struct {
key string
}
var myApiKey ApiKey
func init() {
myApiKey = ApiKey{key: "xcl"}
}
func main() {}
// so导出的函数名
func GetEmailAppKey() func() string {
return myApiKey.GetKey
}
func (k *ApiKey) GetKey() string {
return k.key
}
main.go:
package main
/*
Golang 插件例子, go1.8以上才支持,且例子仅跑在linux上
编译出.so
go build -tags example -o plug3.so -buildmode=plugin plug3/plug3.go
编译主文件
go build -tags example -o plugdemo main.go
使用例子
./plugdemo ./plug3.so
Author: XCL
Date: 2017-7-16
*/
import (
"errors"
"fmt"
"os"
"plugin"
)
const (
fnKey = "GetEmailAppKey"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("请传入.os。")
os.Exit(1)
}
pluginFilename := os.Args[1]
if _, err := os.Stat(pluginFilename); os.IsNotExist(err) {
fmt.Println(".os不存在。")
os.Exit(1)
}
plug, err := plugin.Open(pluginFilename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fn, err := GetPluginKeyFnsByName(plug, fnKey)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
nn := fn()
fmt.Println(" appKey:", nn)
}
func GetPluginKeyFnsByName(p *plugin.Plugin, symbolName string) (func() string, error) {
if p == nil {
return nil, errors.New("p为空指针.")
}
sym, err := p.Lookup(symbolName)
if err != nil {
return nil, err
}
fn, ok := sym.(func() func() string)
if !ok {
return nil, fmt.Errorf("symbol:%T ", sym)
}
if fn() == nil {
return nil, errors.New("fn为空.")
}
return fn(), nil
}
Blog: blog.csdn.net/xcl168