go 1.8 plugin use custom interface
Many Go plugins require the ability to pass complex custom interfaces into them. It is, unfortunately, not currently possible to do this normally in the original plugin implementation.
One way to avoid this problem is to make the plugin return a value of type interface{}. The main application can then define the interface it expects and use type assertion on the interface{} value returned by the plugin.
For example, the plugin code might look like this:
package main import ( "fmt" ) type plgFilter struct{} func (plgFilter) Name() string { return "Bob" } func (plgFilter) Age() int { return 23 } func GetFilterIface() (f interface{}, err error) { f = plgFilter{} fmt.Printf("[plugin GetFilterIface] Returning filter: %T %v\n", f, f) return }
And the main application code might look like this:
package main import ( "fmt" "plugin" ) func main() { p, err := plugin.Open("pg/pg.so") if err != nil { panic(err) } GetFilterIface, err := p.Lookup("GetFilterIface") if err != nil { panic(err) } filterIface, err := GetFilterIface.(func() (interface{}, error))() fmt.Printf("GetFilterIface result: %T %v %v\n", filterIface, filterIface, err) myfilter := filterIface.(MyFilter) fmt.Println("\tName:", myfilter.Name()) fmt.Println("\tAge:", myfilter.Age()) } type MyFilter interface { Name() string Age() int }
Another solution is to define the interface in a package outside of the plugin, and both the plugin and your application can import it and refer to it.
For example, if the interface is defined in package filter:
package filter type Filter interface { Name() string Age() int }
Then the plugin code might look like this:
package main import ( "fmt" "filter" ) type plgFilter struct{} func (plgFilter) Name() string { return "Bob" } func (plgFilter) Age() int { return 23 } func GetFilter() (f filter.Filter, err error) { f = plgFilter{} fmt.Printf("[plugin GetFilter] Returning filter: %T %v\n", f, f) return }
And the main application code might look like this:
package main import ( "fmt" "filter" "plugin" ) func main() { p, err := plugin.Open("pg/pg.so") if err != nil { panic(err) } GetFilter, err := p.Lookup("GetFilter") if err != nil { panic(err) } filter, err := GetFilter.(func() (filter.Filter, error))() fmt.Printf("GetFilter result: %T %v %v\n", filter, filter, err) fmt.Println("\tName:", filter.Name()) fmt.Println("\tAge:", filter.Age()) }
The above is the detailed content of How Can I Pass Custom Interfaces to Go 1.8 Plugins?. For more information, please follow other related articles on the PHP Chinese website!