DEV Community

Cover image for πŸ”Œ Using Plugins in Go: A Simple Introduction
Ray Jones
Ray Jones

Posted on • Edited on

πŸ”Œ Using Plugins in Go: A Simple Introduction

πŸ”§ 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
Enter fullscreen mode Exit fullscreen mode

✏️ 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)
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")
}
Enter fullscreen mode Exit fullscreen mode

▢️ 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
Enter fullscreen mode Exit fullscreen mode

Output

Hello Go Developer
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
anyona_nicholas profile image
anyona nicholas

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 !

Collapse
 
rayjay profile image
Ray Jones

I think you are confusing between a library and plugin.