vibe-d / vibe.d

Official vibe.d development

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how can i do something before serveStaticFiles

rocex opened this issue · comments

commented

I have some html files in the static directory, and then through router.get("/static/*", serveStaticFiles("static/")); I can route to these static files, but in order to access these files do something Restrictions, such as preventing programs like crawlers, how can I do this?

My current practice is to rewrite the HTTPServerRequestDelegateS serveStaticFiles(NativePath local_path, HTTPFileServerSettings settings = null) method, and change sendFileImpl(req, res, local_path ~ rpath, settings); to sendFile(req, res, local_path ~ rpath, settings) ; and do business logic verification before. But doing so will copy a large section of the logic in fileserver.d, which is not conducive to the future upgrade of vibe. Is it possible to add functions such as hooks to serveStaticFiles.callback? I need to get some client information in req , if I can get req before serveStaticFiles maybe it might solve my problem, or there is a better solution?

You can register the same route twice to perform layered handling - if the first handler doesn't throw an exception and doesn't write a response, the request will fall through to the next matching route. So your example could look something like this:

void applyFileRestrictions(scope HTTPServerRequest req, scope HTTPServerResponse res)
{
    if (req.headers.get("User-Agent", "").isCrawler)
        throw new HTTPStatusException(HTTPStatus.forbidden);
}

auto r = new URLRouter;
r.get("/static/*", &applyFileRestrictions);
r.get("/static/*", serveStaticFiles("static/"));
commented

it works, thank you.