To create a basic Go plugin in Golang, follow these steps:
plugin.go
with the following content:package main
import "fmt"
// Exported function to be used as a plugin
func ExportedFunction() {
fmt.Println("Exported function called")
}
// Exported variable to be used as a plugin
var ExportedVariable = 42
-buildmode
flag. Use either plugin
(for Linux and macOS) or --buildmode=plugin
(for Windows). For example, to build the plugin for Linux:go build -buildmode=plugin -o myplugin.so plugin.go
This will create a shared library file called myplugin.so
that contains your exported functionality.
main.go
with the following content:package main
import (
"fmt"
"plugin"
)
func main() {
// Open the plugin
p, err := plugin.Open("myplugin.so")
if err != nil {
fmt.Println("Error opening plugin:", err)
return
}
// Look up the exported function
f, err := p.Lookup("ExportedFunction")
if err != nil {
fmt.Println("Error looking up function:", err)
return
}
// Call the exported function
f.(func())()
// Look up the exported variable
v, err := p.Lookup("ExportedVariable")
if err != nil {
fmt.Println("Error looking up variable:", err)
return
}
// Print the value of the exported variable
fmt.Println("Exported variable:", v.(int))
}
go run main.go
This will load the plugin, call the exported function ExportedFunction
, and print the value of the exported variable ExportedVariable
.