Added configurable user agents that get served the text version by default

This commit is contained in:
Slatian
2023-02-21 10:00:10 +01:00
parent c4379d4c19
commit c7ba9a6346
6 changed files with 71 additions and 3 deletions

View File

@ -35,6 +35,7 @@ pub struct GeoIpConfig {
pub struct TemplateConfig {
pub template_location: String,
pub extra_config: Option<String>,
pub text_user_agents: Vec<String>,
}
impl Default for ServerConfig {
@ -71,6 +72,7 @@ impl Default for TemplateConfig {
TemplateConfig {
template_location: "templates/".to_string(),
extra_config: None,
text_user_agents: vec!["curl/".to_string()],
}
}
}

View File

@ -5,11 +5,13 @@ use axum::{
State,
Extension,
},
headers,
http::Request,
middleware::{self, Next},
response::Response,
Router,
routing::get,
TypedHeader,
};
use axum_client_ip::SecureClientIp;
use clap::Parser;
@ -244,12 +246,26 @@ async fn main() {
async fn format_and_language_middleware<B>(
Query(query): Query<BaseQuery>,
Extension(config): Extension<config::EchoIpServiceConfig>,
user_agent_header: Option<TypedHeader<headers::UserAgent>>,
mut req: Request<B>,
next: Next<B>
) -> Response {
let format = query.format.unwrap_or(ResponseFormat::TextHtml);
let mut format = query.format;
// Try to guess type from user agent
if format.is_none() {
if let Some(TypedHeader(user_agent)) = user_agent_header {
let ua = user_agent.as_str();
for tua in config.template.text_user_agents {
if ua.starts_with(&tua) {
format = Some(ResponseFormat::TextPlain);
break;
}
}
}
}
// Add the request settings extension
req.extensions_mut().insert(TemplateSettings{
format: format,
format: format.unwrap_or(ResponseFormat::TextHtml),
lang: query.lang.unwrap_or("en".to_string()),
});
next.run(req).await