Summary - plugin
- Go course
- Advanced
- Lesson 24/68
- 4 min
Combine the plugin structure to write a plugin system.
plugin summary
The flow: build the plugin with -buildmode=plugin → load it with plugin.Open → get the symbol with Lookup → make a safe type assertion to a function or pointer → use it. Errors are checked at every step.
Limits: no Windows, same Go and dependency versions required, no unloading. Because of these, process-based plugin systems are often preferred.
A command registry example
A CLI tool can open every .so file in a plugins/ folder, look up a Komut symbol and register what it finds in a map:
komutlar := map[string]Komut{}
for _, yol := range dosyalar {
p, err := plugin.Open(yol)
if err != nil { continue }
if s, err := p.Lookup("Komut"); err == nil {
if k, ok := s.(Komut); ok { komutlar[k.Ad()] = k }
}
}Practice Command registry
Define type Komut interface { Ad() string } and type selam struct{}; for selam, Ad() returns "selam". Convert var sym any = selam{} (imitating a plugin symbol) to Komut with a , ok assertion, add it to a map[string]Komut and print the map's length.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Komut interface{ Ad() string }
type selam struct{}
func (selam) Ad() string { return "selam" }
func main() {
komutlar := map[string]Komut{}
var sym any = selam{}
if k, ok := sym.(Komut); ok {
komutlar[k.Ad()] = k
}
fmt.Println(len(komutlar))
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a common alternative to plugins?
- sync.Pool
- Talking to a separate process over gRPC/RPC Correct answer
- unsafe.Pointer
- go:embed
Explanation: Systems such as HashiCorp go-plugin run the plugin in a separate process, removing version coupling and platform limits.
2 Build mode
go build -buildmode=____ -o ek.so ./ek
go build -buildmode=plugin -o ek.so ./ek
Explanation: The plugin build mode produces a .so loadable from Go.
3 Flow
| Term | Meaning |
|---|---|
-buildmode=plugin |
Build |
plugin.Open |
Load |
Lookup |
Symbol |
s.(Komut) |
Type assertion |