Writing a Custom WASM Module in Rust

Set Up Your Development Environment

First, you'll need to set up your environment for WebAssembly development with the tools specific for Envoy:

Install Rust: Since Rust is a popular choice for writing high-performance WebAssembly modules, you'll want to install it along with wasm-pack.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
cargo install wasm-pack

Create a New Rust Library

cargo new --lib meow_wasm_filter
cd meow_wasm_filter

Update your Cargo.toml to include the necessary dependencies

name = "meow_wasm_filter"
version = "0.1.0"
edition = "2021"

proxy-wasm = "0.1.4"
wasm-bindgen = "0.2"
log = "0.4"

crate-type = ["cdylib"]

Write the WebAssembly Code

Now, let’s write the Rust code for the WASM module.

Create the WASM Filter

Edit src/lib.rs to include the following code:

use proxy_wasm::traits::*;
use proxy_wasm::types::*;

pub fn _start() {
    proxy_wasm::set_http_context(|_, _| -> Box<dyn HttpContext> {
        Box::new(HttpBodyChanger {})

struct HttpBodyChanger {}

impl Context for HttpBodyChanger {}

impl HttpContext for HttpBodyChanger {
    fn on_http_response_body(&mut self, _body_size: usize, _end_of_stream: bool) -> Action {
        let body = self.get_http_response_body(0, _body_size).unwrap_or_default();
        let modified_body = String::from_utf8(body).unwrap().replace("the", "meow");
        self.set_http_response_body(0, modified_body.len(), &modified_body.into_bytes());

This code defines a WASM filter that replaces occurrences of "the" with "meow" in the response body of HTTP requests.

Build the WASM Module

Compile the Rust project to generate the WASM binary:

wasm-pack build --target web

Deploy the WASM Module

You'll need to configure Qpoint to use your WASM module. See Configuring the Proxy for more details.

Last updated