plugin

package module
v0.0.0-...-5188de9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2021 License: MIT Imports: 3 Imported by: 0

README

Plugin

This package is a very simple wrapper loading a golang plugin with the goal of making it easier to load in a work with a plugin.

Motivation

Using the plugin golang package directly requires you to manually lookup each property of the plugin you want to load and cast it to something useful. The code to do this just to be able to get at the plugin's properties becomes somewhat tedious boilerplate code. The goal of this package is to allow you to just define an "interface" (through the use of a struct) that you expect from the loaded plugin and this library will "hydrate" that struct with the properties of the plugin. This let's you use the struct in your progress and not have to deal the loading and validating the plugin.

Usage

First, you define a struct to define (and be the instance for) a plugin.

type Adapter struct {
  Hello func(string)   string
  Add   func(int, int) int
  Mult  func(int, int) int     `lookup:"Multiply"`
}

Build the plugin itself.

// ./example/plugin.go
package main

func Hello(name string) string {
	return "Hello " + name + "!"
}

func Add(a, b int) int {
	return a + b
}

func Multiply(a, b int) int {
	return a * b
}
go build --buildmode=plugin -o ./example/plugin.so ./example/plugin.go

Then you load the plugin into an instance of that struct.

instance := Adapter{}

err := plugin.Load(&instance, "./example/plugin.so")
if err != nil {
  log.Fatal(err)
}

fmt.Println( instance.Hello("world") )
fmt.Println( instance.Add(1, 3) )
fmt.Println( instance.Mult(1, 3) )
Testing

You can run the example test with the make command.

make test

It will build the example plugin and run the example that loads it. You can run those commands manually if you want like this:

go generate
go test ./...

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNotAPointer      = fmt.Errorf("not a pointer")
	ErrNotAStruct       = fmt.Errorf("not a struct")
	ErrUnassignableType = fmt.Errorf("unable to assign plugin type to struct type")
	ErrLookupFailed     = fmt.Errorf("plugin property lookup failed")
)

Functions

func Load

func Load(plg interface{}, pathToPlugin string) error
Example
type Adapter struct {
	Hello func(name string) string
	Add   func(int, int) int
	Mult  func(int, int) int `lookup:"Multiply"`
}

loadedPlugin := Adapter{}

err := plugin.Load(&loadedPlugin, "./example/some-plugin.so")
if err != nil {
	log.Fatal(fmt.Errorf("try running `go generate` first : %v", err))
}

fmt.Println(loadedPlugin.Hello("world"))
Output:

Hello world!

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL