该网站的示例:
import vibe.d;
void login(HTTPServerRequest req, HTTPServerResponse res)
{
enforceHTTP("username" in req.form && "password" in req.form,
HTTPStatus.badRequest, "Missing username/password field.");
// todo: verify user/password here
auto session = res.startSession();
session["username"] = req.form["username"];
session["password"] = req.form["password"];
res.redirect("/home");
}
void logout(HTTPServerRequest req, HTTPServerResponse res)
{
res.terminateSession();
res.redirect("/");
}
void checkLogin(HTTPServerRequest req, HTTPServerResponse res)
{
// force a redirect to / for unauthenticated users
if( req.session is null )
res.redirect("/");
}
shared static this()
{
auto router = new URLRouter;
router.get("/", staticTemplate!"index.dl");
router.post("/login", &login);
router.post("/logout", &logout);
// restrict all following routes to authenticated users:
router.any("*", &checkLogin);
router.get("/home", staticTemplate!"home.dl");
auto settings = new HTTPServerSettings;
settings.sessionStore = new MemorySessionStore;
// ...
}
但是可以说我不想将整个程序中的 ServerResponse 传递给每个函数。例如,如果 res.session 存储了当前用户的 id 怎么办。这经常使用,所以我不希望它通过每个函数。如何在全球范围内存储此会话信息?假设有多个用户使用该网站。