Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Zig environment variables example #216

Merged
merged 1 commit into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/docs/features/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ This feature allows you to configure environment variables dynamically.
| Go | ✅ |
| Ruby | ✅ |
| Python | ✅ |
| Zig | |
| Zig | |
40 changes: 20 additions & 20 deletions docs/docs/languages/zig.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ In this example, the worker will get a request and print all the related informa
```c title="worker.zig"
const std = @import("std");
const worker = @import("worker");

fn requestFn(resp: *worker.Response, r: *worker.Request) void {
_ = r;

_ = &resp.headers.append("x-generated-by", "wasm-workers-server");
_ = &resp.writeAll("hello from zig");
}

pub fn main() !void {
worker.ServeFunc(requestFn);
}
```

4. Additionally, you can now go further add all the information from the received `worker.Request`:

```c title="worker.zig"
Expand Down Expand Up @@ -100,7 +100,7 @@ In this example, the worker will get a request and print all the related informa
\\</body>
;

var body = std.fmt.allocPrint(allocator, s, .{ r.url.path, r.method, "-", payload }) catch undefined;
var body = std.fmt.allocPrint(allocator, s, .{ r.url.path, r.method, "-", payload }) catch undefined;

_ = &resp.headers.append("x-generated-by", "wasm-workers-server");
_ = &resp.writeAll(body);
Expand All @@ -121,7 +121,7 @@ In this example, the worker will get a request and print all the related informa
--mod worker::lib/worker.zig \
--deps worker
```

You can also use a build script to build the project with a simple `zig build`, please find some inspiration in our [zig examples](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/).

6. Run your worker with `wws`. If you didn't download the `wws` server yet, check our [Getting Started](../get-started/quickstart.md) guide.
Expand Down Expand Up @@ -220,7 +220,7 @@ To add a KV store to your worker, follow these steps:
--mod worker::lib/worker.zig \
--deps worker
```

You can also use a build script to build the project with a simple `zig build`, please find some inspiration in our [zig examples](https://github.com/vmware-labs/wasm-workers-server/tree/main/examples/).

1. Create a `worker-kv.toml` file with the following content. Note the name of the TOML file must match the name of the worker. In this case we have `worker-kv.wasm` and `worker-kv.toml` in the same folder:
Expand Down Expand Up @@ -258,10 +258,10 @@ You can define [dynamic routes by adding route parameters to your worker files](
```c title="main.zig"
const std = @import("std");
const worker = @import("worker");

fn requestFn(resp: *worker.Response, r: *worker.Request) void {
var params = r.context.params;

...
}
```
Expand All @@ -271,31 +271,31 @@ You can define [dynamic routes by adding route parameters to your worker files](
```c title="main.zig"
const std = @import("std");
const worker = @import("worker");

var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();

fn requestFn(resp: *worker.Response, r: *worker.Request) void {
var params = r.context.params;

var id: []const u8 = "the value is not available";

var v = params.get("id");

if (v) |val| {
id = val;
}

const s =
\\Hey! The parameter is: {s}
;

var body = std.fmt.allocPrint(allocator, s, .{ id }) catch undefined; // add useragent

_ = &resp.headers.append("x-generated-by", "wasm-workers-server");
_ = &resp.writeAll(body);
}

pub fn main() !void {
worker.ServeFunc(requestFn);
}
Expand All @@ -318,7 +318,7 @@ You can define [dynamic routes by adding route parameters to your worker files](

```shell-session
wws .

⚙️ Loading routes from: .
🗺 Detected routes:
- http://127.0.0.1:8080/[id]
Expand All @@ -342,4 +342,4 @@ The Zig kit was originally authored by Christoph Voigt ([@voigt](https://github.

| [K/V Store](../features/key-value.md) | [Environment Variables](../features/environment-variables.md) | [Dynamic Routes](../features/dynamic-routes.md) | [Folders](../features/mount-folders.md) | [HTTP Requests](../features/http-requests.md) |
| --- | --- | --- | --- | --- |
| ✅ | | ✅ | ✅ | ❌ |
| ✅ | | ✅ | ✅ | ❌ |
33 changes: 33 additions & 0 deletions examples/zig-envs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Zig environment variables example

Compile a Zig worker to WebAssembly and run it in Wasm Workers Server.

## Prerequisites

* Wasm Workers Server (wws):

```shell-session
curl -fsSL https://workers.wasmlabs.dev/install | bash
```

* [Zig](https://ziglang.org/download/) `0.11.0`

## Build

All specific build configurations are in `build.zig` file.

```shell-session
zig build
```

## Run

```shell-session
wws ./zig-out/bin/
```

## Resources

* [Environment variables](https://workers.wasmlabs.dev/docs/features/environment-variables)
* [Zig documentation](https://workers.wasmlabs.dev/docs/languages/zig)
* [Announcing Zig support for Wasm Workers Server](https://wasmlabs.dev/articles/Zig-support-on-wasm-workers-server/)
26 changes: 26 additions & 0 deletions examples/zig-envs/build.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const std = @import("std");

const examples = [1][]const u8{ "envs" };

pub fn build(b: *std.Build) !void {
const target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "wasm32-wasi" });
const optimize = b.standardOptimizeOption(.{});

const worker_module = b.createModule(.{
.source_file = .{ .path = "../../kits/zig/worker/src/worker.zig" },
});

inline for (examples) |example| {
const exe = b.addExecutable(.{
.name = example,
.root_source_file = .{ .path = "src/" ++ example ++ ".zig" },
.target = target,
.optimize = optimize,
});

exe.wasi_exec_model = .reactor;
exe.addModule("worker", worker_module);

b.installArtifact(exe);
}
}
25 changes: 25 additions & 0 deletions examples/zig-envs/src/envs.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const std = @import("std");
const worker = @import("worker");

var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();

fn requestFn(resp: *worker.Response, r: *worker.Request) void {
_ = r;

const envvar = std.process.getEnvVarOwned(allocator, "MESSAGE") catch "";
defer allocator.free(envvar);

const s =
\\The environment variable value is: {s}
;

var body = std.fmt.allocPrint(allocator, s, .{ envvar }) catch undefined; // add useragent

_ = &resp.headers.append("x-generated-by", "wasm-workers-server");
_ = &resp.writeAll(body);
}

pub fn main() !void {
worker.ServeFunc(requestFn);
}
5 changes: 5 additions & 0 deletions examples/zig-envs/zig-out/bin/envs.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name = "envs"
version = "1"

[vars]
MESSAGE = "Hello! This message comes from an environment variable"