Write plugins in Go
To write a Kong Gateway plugin in Go, you need to:
- Define a
structure
type to hold configuration. - Write a
New()
function to create instances of your structure. - Add methods to that structure to handle phases.
- Include the
go-pdk/server
sub-library. - Add a
main()
function that callsserver.StartServer(New, Version, Priority)
. - Compile as an executable with
go build
.
The plugin you write needs a way to handle incoming configuration data from the data store or the Admin API. You can use a struct
to create a schema of the incoming data.
Because this plugin will be processing configuration data, you are going to want to control encoding using the encoding/json
package. Go fields that start with a capital letter can be exported, making them accessible outside of the current package, including by the encoding/json
package. If you want the fields to have a different name in the data store, add tags to the fields in your struct
.
Path string `json:"my_file_path"`
Reopen bool `json:"reopen"`
}
func New() interface{} {
return &MyConfig{}
}
Each plugin is compiled as a standalone executable. Include github.com/Kong/go-pdk
in the imports list, and add a main()
function:
Executables can be placed somewhere in your path (for example, /usr/local/bin
). The common -h
flag shows a usage help message:
my-plugin -h
Output:
Usage of my-plugin:
-dump
Dump info about plugins
-help
Show usage info
-kong-prefix string
Kong prefix path (specified by the -p argument commonly used in the Kong CLI) (default "/usr/local/kong")
When you run the plugin without arguments, it creates a socket file within the kong-prefix
and the executable name, appending .socket
. For example, if the executable is my-plugin
, the socket file would be /usr/local/kong/my-plugin.socket
.
You can implement custom logic during the following phases using the same function signature:
Certificate
Rewrite
Response
Preread
Log
The presence of the Response
handler automatically enables the buffered proxy mode.
You can define the version number and priority of execution by declaring the following constants within the plugin code:
const Version = "1.0.0"
const Priority = 1
Kong Gateway executes plugins from highest priority to lowest.
pluginserver_names = my-plugin,other-one
pluginserver_my_plugin_socket = /usr/local/kong/my-plugin.socket
pluginserver_my_plugin_start_cmd = /usr/local/bin/my-plugin
pluginserver_my_plugin_query_cmd = /usr/local/bin/my-plugin -dump
pluginserver_other_one_socket = /usr/local/kong/other-one.socket
pluginserver_other_one_start_cmd = /usr/local/bin/other-one
pluginserver_other_one_query_cmd = /usr/local/bin/other-one -dump
The socket and start command settings coincide with their defaults and can be omitted: