Implement a WASM plugin with Golang

1. Prepare Development Tools

First, install Golang and Tinygo.

1. Golang

Min Version: 1.18
Official download link: https://go.dev/doc/install

Windows

  1. Download the installer: https://go.dev/dl/go1.19.windows-amd64.msi
  2. Run the downloaded installer to start the installation. It will be installed to Program Files or Program Files (x86) folder by default.
  3. After completed the installation, open “Run” dialog with hotkey “Win+R”. Type “cmd” in the dialog and click “OK” to open Command Line Prompt. Type: go version. If version info is displayed, the package has been successfully installed.

MacOS

  1. Download the installer: https://go.dev/dl/go1.19.darwin-amd64.pkg
  2. Run the downloaded installer to start the installation. It will be installed to /usr/local/go folder by default.
  3. Open Terminal and type: go version. If version info is displayed, the package has been successfully installed.

Linux

  1. Download the installer: https://go.dev/dl/go1.19.linux-amd64.tar.gz
  2. Execute following commands to start the installation:
  1. rm -rf /usr/local/go && tar -C /usr/local -xzf go1.19.linux-amd64.tar.gz
  2. export PATH=$PATH:/usr/local/go/bin
  1. Execute go version. If version info is displayed, the package has been successfully installed.

2. TinyGo

Min Version: 0.28.1
Official download link: https://tinygo.org/getting-started/install/

Windows

  1. Download the package: https://github.com/tinygo-org/tinygo/releases/download/v0.28.1/tinygo0.28.1.windows-amd64.zip
  2. Unpack the package to the target folder
  3. If the package is unpacked to folder C:\tinygo, you need to add C:\tinygo\bin into the environment variable PATH, using set command in Command Line Prompt for example.
  1. set PATH=%PATH%;”C:\tinygo\bin”;
  1. Execute tinygo version command in Command Line Prompt. If version info is displayed, the package has been successfully installed.

MacOS

  1. Download and unpack the package
  1. tar -zxf tinygo0.28.1.darwin-amd64.tar.gz
  1. If the package is unpacked to folder /tmp, you need to add /tmp/tinygo/bin to the environment variable PATH:
  1. export PATH=/tmp/tinygo/bin:$PATH
  1. Execute command tinygo version in Terminal. If version info is displayed, the package has been successfully installed.

Linux

Following steps are based on Ubuntu AMD64. For other OSes, please refer to the official document.

  1. Download and install the DEB package.
  1. sudo dpkg -i tinygo_0.28.1_amd64.deb
  2. export PATH=$PATH:/usr/local/bin
  1. Execute command tinygo version in Terminal. If version info is displayed, the package has been successfully installed.

2. Write a plugin

1. Initialize the project

You can create your wasm-go plugin directory in the repo higress’s plugins/wasm-go that you can use the scaffolding tools provided in this directory(see 1.1); or create a new directory for your Go project yourself(see 1.2). If you are developing wasm-go plugins for the first time, it is recommended to take the former.

1.1 create wasm-go plugin in plugins/wasm-go

  1. git clone https://github.com/alibaba/higress.git, to clone project to local;
  2. cd plugins/wasm-go; mkdir wasm-demo-go, to go to the project’s plugins/wasm-go directory and create the wasm-demo-go directory.

1.2 create a new project yourself

  1. Create a new folder for the project. For example: wasm-demo-go.
  2. Execute following commands in the new folder to initialize the Go project:
  1. go mod init wasm-demo-go
  1. If you are in the Chinese mainland, you may need to set a proxy for downloading dependencies.
  1. Download dependencies for plugin building.
  1. go get github.com/tetratelabs/proxy-wasm-go-sdk
  2. go get github.com/alibaba/higress/plugins/wasm-go@main
  3. go get github.com/tidwall/gjson

2. Write main.go

You can find a simple sample below, which provides following functions:

  1. If mockEnable is set to true, send hello world directly as the response.
  2. If mockEnable is not set or set to false, add an extra HTTP header hello: world to the original request. More samples can be found in section 4 below.

Note: Plugin configurations use YAML format in the gateway console. But plugins receive them in JSON format. So in the sample below, actual config data are extracted from JSON by the parseConfig function.

  1. package main
  2. import (
  3. github.com/alibaba/higress/plugins/wasm-go/pkg/wrapper
  4. github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm
  5. github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types
  6. github.com/tidwall/gjson
  7. )
  8. func main() {
  9. wrapper.SetCtx(
  10. // Plugin name
  11. my-plugin”,
  12. // A custom function for parsing plugin configurations
  13. wrapper.ParseConfigBy(parseConfig),
  14. // A custom function for processing request headers
  15. wrapper.ProcessRequestHeadersBy(onHttpRequestHeaders),
  16. )
  17. }
  18. // Custom plugin configuration
  19. type MyConfig struct {
  20. mockEnable bool
  21. }
  22. // Plugin configurations set in the console with YAML format will be converted to JSON. So we just need to parse config data from JSON.
  23. func parseConfig(json gjson.Result, config *MyConfig, log wrapper.Log) error {
  24. // Get the configuration property and set to the config object.
  25. config.mockEnable = json.Get(“mockEnable”).Bool()
  26. return nil
  27. }
  28. func onHttpRequestHeaders(ctx wrapper.HttpContext, config MyConfig, log wrapper.Log) types.Action {
  29. proxywasm.AddHttpRequestHeader(“hello”, world”)
  30. if config.mockEnable {
  31. proxywasm.SendHttpResponse(200, nil, []byte(“hello world”), -1)
  32. }
  33. return types.ActionContinue
  34. }

HTTP Processing Pointcuts

In the sample above, wrapper.ProcessRequestHeadersBy applies custom function onHttpRequestHeaders when processing requests inHTTP request header processing stage. Besides that, you can use following methods to set custom processing functions for various stages.

HTTP Processing StageTrigger TimePointcut Mounting Method
HTTP request header processing stageWhen gateway receives request headers from clientwrapper.ProcessRequestHeadersBy
HTTP request body processing stageWhen gateway receives request body from clientwrapper.ProcessRequestBodyBy
HTTP response header processing stageWhen gateway receives response headers from upstreamwrapper.ProcessResponseHeadersBy
HTTP response body processing stageWhen gateway receives response body from upstreamwrapper.ProcessResponseBodyBy

Utility Functions

In the sample above, proxywasm.AddHttpRequestHeader and proxywasm.SendHttpResponse are two utility methods provided by the plugin SDK. You can find major utility functions in the table below:

CategoryNameUsageAvailable
HTTP Processing Stage(s)
Request Header ProcessingGetHttpRequestHeadersGet all the request headers sent by the clientHTTP request header processing stage
ReplaceHttpRequestHeadersReplace all headers in the request.HTTP request header processing stage
GetHttpRequestHeaderGet the specified header in the request.HTTP request header processing stage
RemoveHttpRequestHeaderRemove the specified header from the request.HTTP request header processing stage
ReplaceHttpRequestHeaderReplace the specified header in the response.HTTP request header processing stage
AddHttpRequestHeaderAdd a new header to the request.HTTP request header processing stage
Request Body ProcessingGetHttpRequestBodyGet the request body received from client.HTTP request body processing stage
AppendHttpRequestBodyAppend the specified binary data to the request body.HTTP request body processing stage
PrependHttpRequestBodyPrepend the specified binary data to the request body.HTTP request body processing stage
ReplaceHttpRequestBodyReplace the entire request body received from client.HTTP request body processing stage
Response Header ProcessingGetHttpResponseHeadersGet all the response headers received from upstream.HTTP response header processing stage
ReplaceHttpResponseHeadersReplace all headers in the response.HTTP response header processing stage
GetHttpResponseHeaderGet the specified header in the response.HTTP response header processing stage
RemoveHttpResponseHeaderRemove the specified header from the response.HTTP response header processing stage
ReplaceHttpResponseHeaderReplace the specified header in the response.HTTP response header processing stage
AddHttpResponseHeaderAdd a new header to the response.HTTP response header processing stage
Response Body ProcessingGetHttpResponseBodyGet the response body received from upstream.HTTP response body processing stage
AppendHttpResponseBodyAppend the specified binary data to the response body.HTTP response body processing stage
PrependHttpResponseBodyPrepend the specified binary data to the response body.HTTP response body processing stage
ReplaceHttpResponseBodyReplace the entire response body with specific data.HTTP response body processing stage
HTTP CallDispatchHttpCallSend an HTTP request.-
GetHttpCallResponseHeadersGet the response headers associated with a DispatchHttpCall call.-
GetHttpCallResponseBodyGet the response body associated with a DispatchHttpCall call.-
GetHttpCallResponseTrailersGet the response trailer associated with a DispatchHttpCall call.-
Respond DirectlySendHttpResponseReturn a specific HTTP response immediately.-
Process ResumingResumeHttpRequestResume the request processing workflow paused before.-
ResumeHttpResponseResume the response processing workflow paused before.-

3. Build WASM file

  • If your project directory is in the plugins/wasm-go directory, see 3.1.
  • If you are using a self-initialized directory, see 3.2.

3.1 Building wasm-go plugin image with scaffolding

The wasm-go plugin can be built quickly with the following command:

  1. $ PLUGIN_NAME=wasm-demo-go make build
  2. image: wasm-demo-go:20230223-173305-3b1a471
  3. output wasm file: extensions/wasm-demo-go/plugin.wasm

This command eventually builds a wasm file and a Docker image. This local wasm file is exported to the specified plugin’s directory and can be used directly for local debugging. You can also use make build-push to build and push the image together. See plugins/wasm-go for more.

3.2 Compile wasm files locally

Execute the following command:

  1. tinygo build -o main.wasm -scheduler=none -target=wasi -gc=custom -tags=’custommalloc nottinygc_finalizer ./main.go

A new file named main.wasm will be created after a successful compilation, which will be used in the local debugging sample below as well.
When using custom plugin function in the cloud native gateway market, you just need to upload this file.

3. Local Debugging

TBD

More Samples

Plugin with No Configuration

If the plugin needs no configuration, just define an empty config struct.

  1. package main
  2. import (
  3. github.com/alibaba/higress/plugins/wasm-go/pkg/wrapper
  4. github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm
  5. github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types
  6. )
  7. func main() {
  8. wrapper.SetCtx(
  9. hello-world”,
  10. wrapper.ProcessRequestHeadersBy(onHttpRequestHeaders),
  11. )
  12. }
  13. type MyConfig struct {}
  14. func onHttpRequestHeaders(ctx wrapper.HttpContext, config MyConfig, log wrapper.Log) types.Action {
  15. proxywasm.SendHttpResponse(200, nil, []byte(“hello world”), -1)
  16. return types.ActionContinue
  17. }

Send Requests to External Services in the Plugin

Only HTTP requests are supported for now. You can send requests to Nacos and K8s services with service sources configured in the gateway console, and services with a static IP or DNS source. Please be noted, HTTP client in the net/http package cannot be used here. You only use the wrapped HTTP client as shown in the sample below.
In the following sample works as below:

  1. Parse service type in the config parsing stage, and generate the corresponding HTTP client.
  2. In the HTTP request header processing stage, send a service request to the configured URL.
  3. Parse response headers and get token value using the specified key.
  4. Set the token value to the headers of the original request.
  1. package main
  2. import (
  3. errors
  4. net/http
  5. strings
  6. github.com/alibaba/higress/plugins/wasm-go/pkg/wrapper
  7. github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm
  8. github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm/types
  9. github.com/tidwall/gjson
  10. )
  11. func main() {
  12. wrapper.SetCtx(
  13. http-call”,
  14. wrapper.ParseConfigBy(parseConfig),
  15. wrapper.ProcessRequestHeadersBy(onHttpRequestHeaders),
  16. )
  17. }
  18. type MyConfig struct {
  19. // The client used to initiate an HTTP request
  20. client wrapper.HttpClient
  21. // Request URL
  22. requestPath string
  23. // Use this key when extracting token header from the service response and setting a header to the request. The value is configurable.
  24. tokenHeader string
  25. }
  26. func parseConfig(json gjson.Result, config *MyConfig, log wrapper.Log) error {
  27. config.tokenHeader = json.Get(“tokenHeader”).String()
  28. if config.tokenHeader == “” {
  29. return errors.New(“missing tokenHeader in config”)
  30. }
  31. config.requestPath = json.Get(“requestPath”).String()
  32. if config.requestPath == “” {
  33. return errors.New(“missing requestPath in config”)
  34. }
  35. serviceSource := json.Get(“serviceSource”).String()
  36. // If serviceSource is set to “ip” or “dns”, serviceName shall be specified when creating the service.
  37. // If serviceSource is set to “nacos” or “k8s”, serviceName shall be set to the original name specified when registering the service.
  38. serviceName := json.Get(“serviceName”).String()
  39. servicePort := json.Get(“servicePort”).Int()
  40. if serviceName == “” || servicePort == 0 {
  41. return errors.New(“invalid service config”)
  42. }
  43. switch serviceSource {
  44. case k8s”:
  45. namespace := json.Get(“namespace”).String()
  46. config.client = wrapper.NewClusterClient(wrapper.K8sCluster{
  47. ServiceName: serviceName,
  48. Namespace: namespace,
  49. Port: servicePort,
  50. })
  51. return nil
  52. case nacos”:
  53. namespace := json.Get(“namespace”).String()
  54. config.client = wrapper.NewClusterClient(wrapper.NacosCluster{
  55. ServiceName: serviceName,
  56. NamespaceID: namespace,
  57. Port: servicePort,
  58. })
  59. return nil
  60. case ip”:
  61. config.client = wrapper.NewClusterClient(wrapper.StaticIpCluster{
  62. ServiceName: serviceName,
  63. Port: servicePort,
  64. })
  65. return nil
  66. case dns”:
  67. domain := json.Get(“domain”).String()
  68. config.client = wrapper.NewClusterClient(wrapper.DnsCluster{
  69. ServiceName: serviceName,
  70. Port: servicePort,
  71. Domain: domain,
  72. })
  73. return nil
  74. default:
  75. return errors.New(“unknown service source: + serviceSource)
  76. }
  77. }
  78. func onHttpRequestHeaders(ctx wrapper.HttpContext, config MyConfig, log wrapper.Log) types.Action {
  79. // Use the Get function of the client to initiate an HTTP Get request.
  80. // The timeout parameter is omitted here, whose default value is 500ms.
  81. config.client.Get(config.requestPath, nil,
  82. // A callback function which will be called asynchronously when receiving the response.
  83. func(statusCode int, responseHeaders http.Header, responseBody []byte) {
  84. // Process the response with a status code other than 200.
  85. if statusCode != http.StatusOK {
  86. log.Errorf(“http call failed, status: %d”, statusCode)
  87. proxywasm.SendHttpResponse(http.StatusInternalServerError, nil,
  88. []byte(“http call failed”), -1)
  89. return
  90. }
  91. // Print out the status code and response body
  92. log.Infof(“get status: %d, response body: %s”, statusCode, responseBody)
  93. // Extract token value from the response header and set the header of the original request
  94. token := responseHeaders.Get(config.tokenHeader)
  95. if token != “” {
  96. proxywasm.AddHttpRequestHeader(config.tokenHeader, token)
  97. }
  98. // Resume the original request processing workflow. Continue the process, so the request can be forwarded to the upstream.
  99. proxywasm.ResumeHttpRequest()
  100. })
  101. // We need to wait for the callback to finish its process.
  102. // Return Pause action here to pause the request processing workflow, which can be resumed by a ResumeHttpRequest call.
  103. return types.ActionPause
  104. }