CodeBlanks Logo Icon CodeBlanks

The plugin package

Learn the basics and limits of the plugin package.

The plugin package

The plugin package lets you load separately compiled Go code (a .so file) at run time and use its functions and variables. It is a way to add features without rebuilding the main program.

p, err := plugin.Open("selam.so")
sym, err := p.Lookup("Selam")

It only works on Linux, FreeBSD and macOS; Windows is not supported.

Limitations

A plugin and the main program must be built with the same Go version and the same dependency versions, or loading fails. A loaded plugin can never be unloaded. That is why many projects prefer systems that talk to separate processes (e.g. HashiCorp go-plugin, gRPC) instead.

Practice Load a plugin

Call plugin.Open("selam.so"). If there is an error print fmt.Println("yüklenemedi") and return; otherwise print fmt.Println("yüklendi"). (The file doesn't exist here, so the output is yüklenemedi.)

Starter code

main.go
package main

import (
    "fmt"
    "plugin"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "plugin"
)

func main() {
    _, err := plugin.Open("selam.so")
    if err != nil {
        fmt.Println("yüklenemedi")
        return
    }
    fmt.Println("yüklendi")
}

Expected output

yüklenemedi

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 On which system does the plugin package <strong>not</strong> work?

  • macOS
  • FreeBSD
  • Windows Correct answer
  • Linux

Explanation: Go plugin support is only for Linux, FreeBSD and macOS; on Windows plugin.Open returns an error.

2 Open a plugin

Question
p, err := plugin.____("eklenti.so")
Answer
p, err := plugin.Open("eklenti.so")

Explanation: plugin.Open loads the .so file and returns a *plugin.Plugin.

3 plugin concepts

Term Meaning
.so file Compiled plugin
plugin.Open Loading
Lookup Symbol lookup
Same Go version Compatibility requirement

All lessons in Advanced