SoFunction
Updated on 2025-03-05

How to implement Go Plugins

Official implementation

golang 1.8 and above provide a new tool for creating shared objects called Plugins. Currently Plugins is only supported on Linux, FreeBSD, and macOS, and only supports golang calls. ​

Use examples to define a

package main

import (
 "log"
)

func init() {
 ("plugin init")
}

type SayHello struct {
}

func (s *SayHello) CallMe(name string) string {
 ("hello ", name)
 return "I am plugin"
}

// SayHelloPlugin export variablesvar SayHelloPlugin SayHello

use-buildmode=pluginMode compiledShared library

go build -o  -buildmode=plugin 

Call the plugin:

package main

import (
 "log"
 "plugin"
)

type CustomPlugin interface {
 CallMe(name string) string
}

func main() {
 // Open the plug-in (concurrency security) p, err := ("")
 if err != nil {
  panic(err)
 }
 // Search for exportable variables or functions in the plugin sayHelloPlugin, err := ("SayHelloPlugin")
 if err != nil {
  panic(err)
 }
 // Assert plugin type if sayHello, ok := sayHelloPlugin.(CustomPlugin); ok {
  (("togettoyou"))
 }
}
go run 

#Output2021/07/28 17:07:21 plugin init
2021/07/28 17:07:21 hello  togettoyou
2021/07/28 17:07:21 I am plugin

Defining a plugin summary:

  • The package name needs to be defined as main
  • There must be exportable variables or functions
  • No main function is needed
  • The init function will be executed first when the plug-in is loaded

Traefik Yaegi implementation

Yaegi is Traefik's open source Go interpreter. Traefik's own plug-in implementation is used by Yaegi. ​

Yaegi runs on the Go runtime and can be used directly as an embedded interpreter or using an interactive shell to interpret the running Go code. However, it only supports Go 1.15 and Go 1.16 (the latest 2 major versions).

Create the code directory structure as follows:

│  
│  
│  
│
└─plugin
    └─src
        └─hello
                
                

There is a point to note here: Yaegi's plug-in needs to be placed in the src directory. ​

inCode:

package hello

import (
 "fmt"
)

func init() {
 ("hello plugin init")
}

func CallMe(msg string) string {
 (msg)
 return "I am plugin"
}

Code:

package main

import (
 "fmt"
 "/traefik/yaegi/interp"
 "/traefik/yaegi/stdlib"
)

func main() {
 // Initialize the interpreter i := ({GoPath: "./plugin/"})

 // Plugins need to use standard libraries if err := (); err != nil {
  panic(err)
 }

 // Import hello package if _, err := (`import "hello"`); err != nil {
  panic(err)
 }

 // Call v, err := ("")
 if err != nil {
  panic(err)
 }
 callMe := ().(func(string) string)
 (callMe("togettoyou"))
}
go run 

#Outputhello plugin init
togettoyou
I am plugin

This is the end of this article about the implementation of Go Plugins plug-in. For more information about Go Plugins, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!