Rework request routing slightly

This commit is contained in:
Emi Simpson 2021-11-09 13:29:57 -05:00
parent 076c5308f3
commit 08e4523f94
Signed by: Emi
GPG key ID: A12F2C2FFDC3D847

View file

@ -1,6 +1,5 @@
use std::borrow::Cow;
use std::io::Cursor;
use std::ops::Deref;
use tiny_http::Header;
use tiny_http::Request;
@ -31,8 +30,7 @@ pub fn go(domains: &[&str]) {
/// Each route represents a set of logic that should be used to respond to the request,
/// and the necessary information from the request in order to do so
pub enum Route<'a> {
Next(&'a str),
Prev(&'a str),
PrevOrNext(&'a str, isize),
NotFound,
}
@ -40,20 +38,17 @@ impl<'a> Route<'a> {
/// Given a request, parse out the appropriate Route for that request
pub fn parse_request(r: &'a Request) -> Self {
let segments: Vec<_> = r.url()
.split('/')
.filter(|s| !s.is_empty())
.collect();
let (first_segment, referrer_domain) = r.url()
.trim_matches('/')
.split_once('/')
.unwrap_or((r.url(), "missing_referrer_domain"));
// TODO automatically detect a fallback url from the request's Referer header
let referrer_domain = segments.get(1).map(|s| *s).unwrap_or("missing_referrer_domain");
match segments.get(0).map(Deref::deref) {
Some("next") => {
Route::Next(referrer_domain)
match first_segment {
"next" => {
Route::PrevOrNext(referrer_domain, 1)
},
Some("prev") => {
Route::Prev(referrer_domain)
"prev" => {
Route::PrevOrNext(referrer_domain, -1)
},
_ => Route::NotFound,
}
@ -62,13 +57,7 @@ impl<'a> Route<'a> {
/// Generate a Response for this route
pub fn render<'b>(&self, domains: &[&'b str]) -> Response<Cursor<Cow<'b, [u8]>>> {
match self {
Self::Next(this_domain) | Self::Prev(this_domain) => {
let offset: isize = if let Self::Next(_) = self {
1
} else {
-1
};
Self::PrevOrNext(this_domain, offset) => {
let destination = domains.iter()
.position(|d| d.starts_with(this_domain))