Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add properties for accessing the current request and response of a web interface #1938

Merged
merged 1 commit into from
Sep 23, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions web/vibe/web/web.d
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,84 @@ body
return getRequestContext().language;
}

/**
Returns the current request.

Note that this may only be called from a function/method
registered using registerWebInterface.
*/
@property HTTPServerRequest request() @safe
{
return getRequestContext().req;
}

///
@safe unittest {
void requireAuthenticated()
{
auto authorization = "Authorization" in request.headers;

enforceHTTP(authorization !is null, HTTPStatus.forbidden);
enforceHTTP(*authorization == "secret", HTTPStatus.forbidden);
}

class WebService {
void getPage()
{
requireAuthenticated();
}
}

void run()
{
auto router = new URLRouter;
router.registerWebInterface(new WebService);

auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, router);
}
}

/**
Returns the current response.

Note that this may only be called from a function/method
registered using registerWebInterface.
*/
@property HTTPServerResponse response() @safe
{
return getRequestContext().res;
}

///
@safe unittest {
void logIn()
{
auto session = response.startSession();
session.set("token", "secret");
}

class WebService {
void postLogin(string username, string password)
{
if (username == "foo" && password == "bar") {
logIn();
}
}
}

void run()
{
auto router = new URLRouter;
router.registerWebInterface(new WebService);

auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, router);
}
}

/**
Terminates the currently active session (if any).

Expand Down