karlseguin / websocket.zig

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

What is proper way of storing per socket data? #38

Closed mbaracz closed 1 month ago

mbaracz commented 1 month ago

Hello, first of all, I have to say that I am a beginner in Zig. I would like to know how to properly assign data to a connection, such as a token obtained during a handshake that is used later when handling received message. In the documentation, there is only information on how to pass a global context used for each connection.

I would be grateful for any guidance on this matter.

karlseguin commented 1 month ago

When you call websocket.listen the first argument is the type of a "Handler", H. On every connection, H.init is called which is expected to return an instance of H. Any message received from that point on is called on that instance of H. Your Handler can be any structure, and thus can hold any user-specific (or global) data it wants.

There's also the optional afterInit which is called on your instance of *H which would then let you, for examlpe, add this handler to a "rooms" hashmap or something, so that you can reference this in your own code.

Roughly, something like:

const Handler = struct {
    id: u32,
    app: *App,
    conn: *Conn,

    pub fn init(h: Handshake, conn: *Conn, app: *App) !Handler {
        const id = getUserIdFromHandshake(h);
        return Handler{
            .id = id,
            .app = app,
            .conn = conn,
        };
    }

    pub fn afterInit(self: *Handler) !void {
        try self.app.users.append(self.id, self);
    }
};