Golang plugin 插件例子

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





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值