Add some more Response types
This commit is contained in:
parent
55fb3a196e
commit
aaa062db31
3 changed files with 148 additions and 1 deletions
|
@ -1,7 +1,58 @@
|
|||
use tiny_http::{Request, Response};
|
||||
use ascii::AsciiString;
|
||||
use maud::Markup;
|
||||
use tiny_http::{Header, Request, Response};
|
||||
|
||||
/// Returns a 404 response
|
||||
pub fn respond_not_found(request: Request) {
|
||||
let response = Response::from_string("Not Found").with_status_code(404);
|
||||
|
||||
let _ = request.respond(response);
|
||||
}
|
||||
|
||||
/// Renders html
|
||||
pub fn respond_html(request: Request, content: Markup) {
|
||||
let response = Response::from_string(content);
|
||||
let response = response.with_header(Header {
|
||||
field: "Content-Type".parse().unwrap(),
|
||||
value: AsciiString::from_ascii("text/html; charset=utf8").unwrap(),
|
||||
});
|
||||
|
||||
let _ = request.respond(response);
|
||||
}
|
||||
|
||||
/// Redirects the user to another route
|
||||
pub fn respond_redirect(request: Request, new_route: &str) {
|
||||
let response = Response::from_string("Redirect");
|
||||
let response = response.with_header(Header {
|
||||
field: "Content-Type".parse().unwrap(),
|
||||
value: AsciiString::from_ascii("text/html").unwrap(),
|
||||
});
|
||||
let response = response.with_header(Header {
|
||||
field: "Location".parse().unwrap(),
|
||||
value: AsciiString::from_ascii(new_route).unwrap(),
|
||||
});
|
||||
let response = response.with_status_code(302);
|
||||
|
||||
let _ = request.respond(response);
|
||||
}
|
||||
|
||||
/// Redirects the user to another route while also adding a cookie
|
||||
pub fn respond_redirect_cookie(request: Request, new_route: &str, cookie_name: &str, cookie_value: &str) {
|
||||
let response = Response::from_string("Redirect")
|
||||
.with_header(Header {
|
||||
field: "Content-Type".parse().unwrap(),
|
||||
value: AsciiString::from_ascii("text/html").unwrap(),
|
||||
})
|
||||
.with_header(Header {
|
||||
field: "Location".parse().unwrap(),
|
||||
value: AsciiString::from_ascii(new_route).unwrap(),
|
||||
})
|
||||
.with_header(Header {
|
||||
field: "Set-Cookie".parse().unwrap(),
|
||||
value: AsciiString::from_ascii(format!("{}={}", cookie_name, cookie_value)).unwrap(),
|
||||
})
|
||||
.with_status_code(302);
|
||||
|
||||
|
||||
let _ = request.respond(response);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue