forked from grandinetech/grandine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_api_config.rs
43 lines (36 loc) · 1.1 KB
/
http_api_config.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use core::{
net::{IpAddr, Ipv4Addr, SocketAddr},
time::Duration,
};
use anyhow::Result;
use tokio::net::TcpListener;
use tower_http::cors::AllowOrigin;
#[derive(Clone, Debug)]
pub struct HttpApiConfig {
pub address: SocketAddr,
pub allow_origin: AllowOrigin,
// `HttpApiConfig.timeout` is optional to prevent timeouts in tests.
pub timeout: Option<Duration>,
}
impl Default for HttpApiConfig {
fn default() -> Self {
Self::with_address(Ipv4Addr::LOCALHOST, 5052)
}
}
impl HttpApiConfig {
#[must_use]
pub fn with_address(ip_address: impl Into<IpAddr>, port: u16) -> Self {
let address = (ip_address, port).into();
let allowed_origin = format!("http://{address}")
.try_into()
.expect("http:// followed by a socket address should be a valid header value");
Self {
address,
allow_origin: AllowOrigin::list([allowed_origin]),
timeout: None,
}
}
pub(crate) async fn listener(&self) -> Result<TcpListener> {
TcpListener::bind(&self.address).await.map_err(Into::into)
}
}