How to Use the Go Plugin System (plugin Package)

Compile code with -buildmode=plugin and load it at runtime using plugin.Open and Lookup to extend your Go application dynamically.

Use the plugin package to compile code as a shared library with -buildmode=plugin, then load it at runtime using plugin.Open and retrieve symbols with Lookup.

// 1. Build the plugin: go build -buildmode=plugin -o myplugin.so myplugin.go
// 2. Load and use it in your main program:
package main

import (
	"fmt"
	"log"
	"plugin"
)

func main() {
	p, err := plugin.Open("myplugin.so")
	if err != nil {
		log.Fatal(err)
	}

	// Retrieve a symbol (must be exported)
	sym, err := p.Lookup("MyFunction")
	if err != nil {
		log.Fatal(err)
	}

	// Type assert and call
	fn := sym.(func() string)
	fmt.Println(fn())
}

Note: Both the host and plugin must be built with CGO enabled (CGO_ENABLED=1) and share the same module path for common dependencies.