π§ What Are Go Plugins?
A plugin in Go is a .so
(shared object) file built from a Go package. It can be loaded at runtime using Goβs plugin package, allowing you to call its functions and access its variables dynamically.
Plugins are supported on Linux and macOS (not Windows).
Create a directory with this similar structure.
go-plugin-tutorial/ βββ main.go # the main program that loads the plugin βββ plugin/ β βββ greet.go # Plugin code
βοΈ Step 1: Create the Plugin
package main import "fmt" // the variables or functions must be exported func Greet(name string) { fmt.Printf("Hello %s\n",name) }
Important: the plugin must use package main and exported symbols (capitalized).
π οΈ Step 2: Build the Plugin
From the root directory, run:
go build -buildmode=plugin -o greet.so plugin/greet.go
This generates greet.so, a shared object file you can load at runtime.
π‘ Step 3: Load the Plugin in Your App
package main import ( "plugin" "log" ) func main() { // Load plugin plug, err := plugin.Open("plugin/greet.so") if err != nil { log.Fatal(err) } // Lookup exported symbol symGreet, err := plug.Lookup("Greet") if err != nil { log.Fatal(err) } // Assert that it's a function with the right signature greetFunc, ok := symGreet.(func(string)) if !ok { log.Fatal("unexpected type from module symbol") } // Call it! greetFunc("Go Developer") }
βΆοΈ Step 4: Run It
Make sure greet.so is in the same directory as main.go or provide accurate path and run:
go run main.go
Output
Hello Go Developer
Top comments (2)
With Golang, this feels repetitive - the library creator declares the functions, then the library user also AGAIN declares the same function.
With C/C++, only the library creator declares the function, the library users just include an header file with
#include <plugin.h>
then links to the library.I wonder why Golang would come late in the game, and make work even more difficult !
I think you are confusing between a library and plugin.