-
Notifications
You must be signed in to change notification settings - Fork 0
Responses
Responses are defined using the Response
type but one should always opt to use the provided helper functions listed below when possible.
struct Response {
http_status_code status;
vector<string> headers;
string content_type;
string body;
};
There are multiple functions to automate response creation.
Creates a response from a SplashKit HTTP status code.
Response status(http_status_code status);
Creates a plain text response.
Response plain(string text, http_status_code status = HTTP_STATUS_OK);
Creates a JSON response from a SplashKit json
type.
Response json_data(json data, http_status_code status = HTTP_STATUS_OK);
Basic HTML templating is available using the html()
function.
Response html(string filename, HtmlVars vars, http_status_code status = HTTP_STATUS_OK);
HTML template variables take the form of an identifier wrapped in curly braces and are replaced by the value which has the same name as the template variable in the vars
hashmap. For an example
<h1>Hello {name}</h1>
return html("hello.html", {{"name", "Hayley"}});
would become
<h1>Hello Hayley</h1>
If a HTML template does not have a matching key in the vars
hashmap then it will be ignored.
The 303 See Other
redirects can be created using the redirect()
function.
Response redirect(string location);
// Example
redirect("/login"); // Creates a redirect to /login
Cookies can be created by passing a Cookie
to the add_cookie()
method of a Response
. For an example
// Create a cookie named user
Cookie c = Cookie("user", "admin");
// Send the cookie it to the client, the response type is irrelevent
plain("User created", HTTP_STATUS_CREATED).add_cookie(c);
If a HTTP 4xx or 5xx status code is thrown any stage during a middleware or route, the corresponding error page will be immediately returned to the client. For an example
throw HTTP_STATUS_UNAUTHORIZED;
will result the unauthorized error handler being used to handle that request.