karlseguin / websocket.zig

A websocket implementation for zig
MIT License
283 stars 25 forks source link

What is the use of the context #15

Closed hajsf closed 11 months ago

hajsf commented 11 months ago

At the server example, you are using a Context I could not figure out what it is, and why it is used?

karlseguin commented 11 months ago

Context is whatever you want it to be. It gets passed to your Handler's init funciton.

In another language, you might use a closure to capture some configuration data, or maybe use global variables. Zig has no closures, and global variables are, at best, cumbersome. So this is the alternative.

Say you were building a chat app, your context might include something like a ChannelManager and UserManager:

var context = Context{.users = your_user_manager, .channels = your_channel_manager}
try websocket.listen(Handler, allocator, &context, .{
    .port = 9223,
    .max_headers = 10,
    .address = "127.0.0.1",
});

....
const Handler = struct {
    conn: *Conn,
    context: *Context,

   pub fn init(_: Handshake, conn: *Conn, context: *Context) !Handler {
        return Handler{
            .conn = conn,
            .context = context,
        };
    }

    pub fn handle(self: *Handler, message: Message) !void {
        // now you have have access to self.context.channels
    }
}

You pass a context to listen, and listen passes that context to your init, where you'll probably store it in your handler and then have access to it in the handle method as self.context.

In simpler cases, a void context would be expected. Or you might have some other app-specific mechanism for sharing data.