Comptime as Configuration

submited by
Style Pass
2025-01-10 05:30:06

If you look at my httpz library, you'll notice that httpz.Server(T) is a generic. The type passed to Server serves two purposes. The first is to support an application-specific context - whatever instance of T passed into Server(T).init gets passed back to your custom HTTP handlers.

But the other purpose of T is to act as a configuration object. For example, if you want to circumvent most of httpz' request processing, you can define a T.handle method:

This is how Jetzig uses httpz. In my Basic MetaProgramming post, we looked at how a few of Zig's built-in functions and std.meta namespace can help us write this kind of code. For the specific case of the handle override, it looks something like:

The return-type check is there to make it clear that the custom handle cannot return an error (or anything else). There are a few different possible overrides in httpz, but they're more or less variations of the above.

One reason I went with this approach is that, as with httpz, the type is needed anyways. Like httpz, it's possible to extend the functionality of ztl and add a application-specific context. The obviously downside is that the user of the library has to create a comptime-known configuration.

Leave a Comment