Build.zig webserver?

For projects where I’m building wasm and testing in a browser, I need to serve the files from a real httpd to allow cross-origin-resource-sharing. Just opening files directly in a browser doesn’t work.

Does anyone know of a way to run a zig httpd from build.zig to serve the produced artefacts?

My current solution is a dockerised httpd as I don’t want to assume that other developers have particular tools. A zig solution which is handled transparently by build.zig would be much better.

2 Likes

I guess I also want auto-reloading when code changes, which this would definitely help with introduce file system watching features to the zig build system by andrewrk · Pull Request #20580 · ziglang/zig · GitHub

Adding a basic static web server to replace my docker+python requirement turned out to be simple with GitHub - andrewrk/StaticHttpFileServer: Zig module for serving a directory of files from memory via HTTP

This thread mentions watchexec Zig watch similar to cargo watch - #3 by andrewrk

Combining them both for my project:

watchexec -r --stop-signal SIGKILL -e zig,html,css,zon -w src 'zig build && zig build serve -- zig-out -p 8000'

6 Likes

In the future you should be able to use the --watch flag (to zig build) for this. I believe there is still a component missing that would enable this which is a way for a process spawned by the build runner to hook into the watch system and receive events.

However, that mechanism isn’t really needed for HTTP servers because there’s a simpler way - make that package support serving the files from disk rather than memory (or make an alternative package that does that), in which case --watch already works as-is.

Still, the build system event mechanism is a general-purpose solution to arbitrary build graphs, and so it could be made to work for HTTP servers that serve from in-memory as well, at least as a proof-of-concept. You could imagine a more complicated scenario where it needs to perform some application-specific logic in order to maintain data invariants that go beyond serving files from disk.

Edit: ah looks like I already filed an issue for this:

5 Likes