Skip to content

WebAssembly Development and Testing

Alex Browne edited this page Mar 22, 2019 · 2 revisions

Pion WebRTC can be used when compiled to WebAssembly, also known as Wasm. In this case the library will act as a wrapper around the JavaScript WebRTC API. This allows you to use WebRTC from Go in both server and browser side code with little to no changes.

This page includes some information about how to run the tests in pions/webrtc repository in a Node.js/Wasm environment as well as general tips for using the Wasm bindings. You can read the Go WebAssembly Wiki for more information about how Go and WebAssembly fit together.

For Contributors

The Wasm bindings work by importing the syscall/js package and using it to make calls to the JavaScript WebRTC API. Before working on the Wasm bindings directly, you are encouraged to read through the documentation for the syscall/js package.

Build tags

The Go compiler uses build tags to differentiate code which is compatible with WebAssembly from code that is not.

Any files which import the syscall/js package must have the +build js build tag. This tells the Go compiler that the file should only be included for WebAssembly builds. In contrast, any files which are not compatible with WebAssembly have the +build !js build tag. Finally, any files which work in both WebAssembly and vanilla Go do not have any build tags.

Testing

The pions/webrtc repository includes tests which can be run in a Node.js/Wasm environment. To run these tests, use the following steps:

  • Install Node.js version >= 10.
  • Install the Yarn package manager (usually just npm i -g yarn).
  • Run yarn install in the root of the repository. This will install the wrtc package which is required because Node.js does not support WebRTC out of the box.

Now you can run the tests in a Node.js/Wasm environment by running GOOS=js GOARCH=wasm go test -exec="./test-wasm/go_js_wasm_exec" -v . in the root of the repository.

Editor Configuration

WebAssembly support is new to Go and some editors may not work correctly out of the box.

Visual Studio Code

For VS Code, some features like auto-complete and go-to-definition will not work for files with the +build js build tag. If you are working on files with that build tag, you can add the following to your settings.json:

"go.toolsEnvVars": {
  "GOARCH": "wasm",
  "GOOS": "js"
},
"go.testEnvVars": {
  "GOARCH": "wasm",
  "GOOS": "js"
}

Now all features should work for files with the +build js build tag. However, leaving these settings in settings.json means that files with the opposite build tag +build !js will no longer work. Unfortunately, for now, you may need to toggle the setting back and forth if you are switching between files with different build tags. The issue can be tracked here and is already improving.