Search code examples
dvibed

Why we should pass pointer in listenHTTP to &handleRequest?


I am reading vibed examples and can't understand next moment:

import vibe.d;

shared static this()
{
    auto settings = new HTTPServerSettings;
    settings.port = 8080;

    listenHTTP(settings, &handleRequest);
}

void handleRequest(HTTPServerRequest req,
                   HTTPServerResponse res)
{
    if (req.path == "/")
        res.writeBody("Hello, World!", "text/plain");
}

Why we are passing in listenHTTP pointer to &handleRequest. I mean why we can't simply call it for every request?

And what about HTTPServerRequest req and HTTPServerResponse res? Are they are creating in moment of handleRequest calling or when?


Solution

  • The pointer is how the library knows what function you want it to call on every request.

    You pass it the pointer to the function, then vibe creates the req and res at that point and calls the pointed to function each time it gets a new request.

    If you tried to pass handleRequest without the pointer, it would try to call it at setup time, before a request was actually ready.