Writing Modular Go Programs with Plugins

Vladimir Vivien
Apr 3, 2017 · 7 min read

The Go plugin

Restrictions

A simple pluggable program

Greeter plugin example layout
package main

import "fmt"

type greeting string

func (g greeting) Greet() {
fmt.Println("Hello Universe")
}

// exported as symbol named "Greeter"
var Greeter greeting

Compiling the Plugins

go build -buildmode=plugin -o eng/eng.so eng/greeter.go
go build -buildmode=plugin -o chi/chi.so chi/greeter.go
$> file chi/chi.so
chi/chi.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=20c823671954b4716d8d945c3b333fc18cdbf7fe, not stripped

Using the Plugins

package main

import "plugin"; ...


type Greeter interface {
Greet()
}

func main() {
// determine plugin to load
lang := "english"
if len(os.Args) == 2 {
lang = os.Args[1]
}
var mod string
switch lang {
case "english":
mod = "./eng/eng.so"
case "chinese":
mod = "./chi/chi.so"
default:
fmt.Println("don't speak that language")
os.Exit(1)
}

// load module
// 1. open the so file to load the symbols
plug, err := plugin.Open(mod)
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// 2. look up a symbol (an exported function or variable)
// in this case, variable Greeter
symGreeter, err := plug.Lookup("Greeter")
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// 3. Assert that loaded symbol is of a desired type
// in this case interface type Greeter (defined above)
var greeter Greeter
greeter, ok := symGreeter.(Greeter)
if !ok {
fmt.Println("unexpected type from module symbol")
os.Exit(1)
}

// 4. use the module
greeter.Greet()

}

Running the program

> go run greeter.go english
Hello Universe
> go run greeter.go chinese
你好宇宙

Modular Go Program Design

Clear affordances

Plugin Independence

Apply Unix modularity principles

Clearly documented

Use interface types as boundaries

New deployment paradigm

Trust and security

Versioning

Gosh: a pluggable command shell

Conclusion

Learning the Go Programming Language

Short and insightful posts for newcomers learning the Go programming language

Vladimir Vivien

Written by

Software Eng • Go Programming • Kubernetes • Author http://golang.fyi

Learning the Go Programming Language

Short and insightful posts for newcomers learning the Go programming language