加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang plugin 插件例子

发布时间:2020-12-16 18:09:42 所属栏目:大数据 来源:网络整理
导读:好像手上有场景可以用Go1.8的插件来弄,写了个例子. plug3/plug3.go: package main/*封装Key到.soAuthor: XCLDate: 2017-7-16*/type ApiKey struct {key string}var myApiKey ApiKeyfunc init() {myApiKey = ApiKey{key: "xcl"}}func main() {}// so导出的函

好像手上有场景可以用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读