当前位置: 首页 > 工具软件 > Yaegi > 使用案例 >

go插件化 yaegi

葛阳
2023-12-01

```go
import (
	"bytes"
	"fmt"

	"github.com/traefik/yaegi/interp"
	"github.com/traefik/yaegi/stdlib"
	"path/filepath"
	"reflect"
)
func main() {
	goPath, err := filepath.Abs(filepath.FromSlash("./_pkg12/"))
	if err != nil {

	}
	i := interp.New(interp.Options{GoPath: goPath})

	// Use binary standard library
	if err := i.Use(stdlib.Symbols); err != nil {

	}

	// Load pkg from sources
	topImport := "github.com/foo/pkg"
	topImport2 := "fmt"
	if topImport != "" {
		topImport = topImport
	}
	_, err = i.Eval(fmt.Sprintf(`import "%s"`, topImport))
	if err != nil {
		panic(err)
	}

	_, err = i.Eval(`pkg.NewSample()`)
	if err != nil {
		panic(err)
	}
	_, err = i.Eval(fmt.Sprintf(`import "%s"`, topImport2))
	if err != nil {
		panic(err)
	}

	_, err = i.Eval(`fmt.Println("3222")`)
	if err != nil {
		panic(err)
	}
}

 类似资料: