Skip to main content

anvil_server/
config.rs

1use crate::HeaderValue;
2use axum::http::header::InvalidHeaderValue;
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use std::str::FromStr;
5
6/// Additional server options.
7#[derive(Clone, Debug, Serialize, Deserialize)]
8#[cfg_attr(feature = "clap", derive(clap::Parser), command(next_help_heading = "Server options"))]
9pub struct ServerConfig {
10    /// The cors `allow_origin` header
11    #[cfg_attr(feature = "clap", arg(long, default_value = "*"))]
12    pub allow_origin: HeaderValueWrapper,
13
14    /// Disable CORS.
15    #[cfg_attr(feature = "clap", arg(long, conflicts_with = "allow_origin"))]
16    pub no_cors: bool,
17
18    /// Disable the default request body size limit. At time of writing the default limit is 2MB.
19    #[cfg_attr(feature = "clap", arg(long))]
20    pub no_request_size_limit: bool,
21}
22
23impl ServerConfig {
24    /// Sets the "allow origin" header for CORS.
25    pub fn with_allow_origin(mut self, allow_origin: impl Into<HeaderValueWrapper>) -> Self {
26        self.allow_origin = allow_origin.into();
27        self
28    }
29
30    /// Whether to enable CORS.
31    pub const fn set_cors(mut self, cors: bool) -> Self {
32        self.no_cors = !cors;
33        self
34    }
35}
36
37impl Default for ServerConfig {
38    fn default() -> Self {
39        Self {
40            allow_origin: "*".parse::<HeaderValue>().unwrap().into(),
41            no_cors: false,
42            no_request_size_limit: false,
43        }
44    }
45}
46
47#[derive(Clone, Debug)]
48pub struct HeaderValueWrapper(pub HeaderValue);
49
50impl FromStr for HeaderValueWrapper {
51    type Err = InvalidHeaderValue;
52
53    fn from_str(s: &str) -> Result<Self, Self::Err> {
54        Ok(Self(s.parse()?))
55    }
56}
57
58impl Serialize for HeaderValueWrapper {
59    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60    where
61        S: Serializer,
62    {
63        serializer.serialize_str(self.0.to_str().map_err(serde::ser::Error::custom)?)
64    }
65}
66
67impl<'de> Deserialize<'de> for HeaderValueWrapper {
68    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69    where
70        D: Deserializer<'de>,
71    {
72        let s = String::deserialize(deserializer)?;
73        Ok(Self(s.parse().map_err(serde::de::Error::custom)?))
74    }
75}
76
77impl std::ops::Deref for HeaderValueWrapper {
78    type Target = HeaderValue;
79
80    fn deref(&self) -> &Self::Target {
81        &self.0
82    }
83}
84
85impl From<HeaderValueWrapper> for HeaderValue {
86    fn from(wrapper: HeaderValueWrapper) -> Self {
87        wrapper.0
88    }
89}
90
91impl From<HeaderValue> for HeaderValueWrapper {
92    fn from(header: HeaderValue) -> Self {
93        Self(header)
94    }
95}