Add some more Response types
All checks were successful
Cargo Build & Test / Tests (pull_request) Successful in 19s
Cargo Build & Test / check-cargo-version (pull_request) Successful in 5s
Cargo Build & Test / Test publish (pull_request) Successful in 16s

This commit is contained in:
Jan K9f 2024-08-20 22:11:40 +02:00
commit aaa062db31
3 changed files with 148 additions and 1 deletions

View file

@ -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);
}