Skip to content

Commit

Permalink
feat: use header HOST instead of path to redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
Cyrix126 committed Jul 8, 2024
1 parent 3e69f9f commit a4adde1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 23 deletions.
6 changes: 4 additions & 2 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use axum::{
};
use enclose::enc;
use reqwest::{
header::{ETAG, VARY},
header::{ETAG, HOST, VARY},
StatusCode,
};
use tokio::spawn;
Expand Down Expand Up @@ -79,7 +79,9 @@ pub async fn handler(State(state): State<AppState>, request: Request) -> impl In
.cloned()
.unwrap_or(PathAndQuery::from_static(""));
debug!("response was not cached, requesting backend service");
let url_backend = state.config.to_backend_uri(&req_uri);
let url_backend = state
.config
.to_backend_uri(&req_uri, request.headers().get(HOST));
debug!("Request URI retrieved: {req_uri}");
debug!("Request URL transmitted:{url_backend}");
let req = state
Expand Down
33 changes: 15 additions & 18 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{
time::Duration,
};

use axum::http::uri::PathAndQuery;
use axum::http::{uri::PathAndQuery, HeaderValue};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use tracing::debug;
Expand All @@ -17,7 +17,7 @@ use tracing::debug;
pub struct Config {
/// address and port to which Mnemosyne will listen for incoming requests.
pub listen_address: SocketAddr,
/// String is the path mnemosyne will accept request and redirect them to Url
/// String is the HOST mnemosyne will accept request and redirect them to Url
pub endpoints: Vec<(String, Url)>,
/// if none of the request contained recognized uri or if you want to redirect every request to one backend.
pub fall_back_endpoint: Url,
Expand All @@ -37,24 +37,21 @@ impl Default for Config {
}

impl Config {
pub fn to_backend_uri(&self, uri_request: &PathAndQuery) -> Url {
pub fn to_backend_uri(&self, uri_req: &PathAndQuery, host: Option<&HeaderValue>) -> Url {
//todo use regex to get the start of the line
if let Some((endpoint, url)) = self
.endpoints
.iter()
.find(|b| uri_request.as_str().starts_with(&b.0))
{
debug!("endpoint detected: {endpoint}");
let new_uri = uri_request.to_string().replace(endpoint, "");
debug!("url: {url}");
debug!("new uri: {new_uri}");
Url::parse(&format!("{}{}", url, new_uri).replace("//", "/"))
.expect("could not parse to Url")
} else {
// no uri recognized, using fallback backend
Url::parse(&format!("{}{}", self.fall_back_endpoint, uri_request).replace("//", "/"))
.expect("could not parse to Url")
if let Some(host) = host {
if let Ok(host) = host.to_str() {
if let Some((endpoint, url)) = self.endpoints.iter().find(|b| host == b.0) {
debug!("endpoint detected: {endpoint}");
debug!("url: {url}");
return Url::parse(&format!("{}{}", url, uri_req).replace("//", "/"))
.expect("could not parse to Url");
}
}
}
// no uri recognized, using fallback backend
Url::parse(&format!("{}{}", self.fall_back_endpoint, uri_req).replace("//", "/"))
.expect("could not parse to Url")
}
}

Expand Down
10 changes: 7 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ fn new_state(config: Config) -> AppState {
// backend
mod test {
use anyhow::Result;
use axum::{routing::get, Router};
use axum::{http::HeaderValue, routing::get, Router};
use axum_test::TestServer;
use reqwest::header::HOST;
use tokio::{net::TcpListener, spawn};
use url::Url;

Expand All @@ -92,7 +93,7 @@ mod test {
// configuration of Mnemosyne
let config = Config {
endpoints: vec![(
"/test".to_string(),
"example.com".to_string(),
Url::parse(&format!("http://127.0.0.1:{port}"))?,
)],
..Default::default()
Expand All @@ -104,7 +105,10 @@ mod test {
// start Mnemosyne
let app = TestServer::new(router).unwrap();
// send get request for the first time
let rep = app.get("/test").await;
let rep = app
.get("/")
.add_header(HOST, HeaderValue::from_static("example.com"))
.await;
rep.assert_status_ok();
Ok(())
}
Expand Down

0 comments on commit a4adde1

Please sign in to comment.