Skip to main content

trillium/
info.rs

1use std::net::SocketAddr;
2use trillium_http::{HttpConfig, HttpContext, Swansong, TypeSet, type_set::entry::Entry};
3
4/// This struct represents information about the currently connected
5/// server.
6///
7/// It is passed to [`Handler::init`](crate::Handler::init).
8
9#[derive(Debug, Default)]
10pub struct Info(HttpContext);
11impl From<HttpContext> for Info {
12    fn from(value: HttpContext) -> Self {
13        Self(value)
14    }
15}
16impl From<Info> for HttpContext {
17    fn from(value: Info) -> Self {
18        value.0
19    }
20}
21
22impl AsRef<TypeSet> for Info {
23    fn as_ref(&self) -> &TypeSet {
24        self.0.as_ref()
25    }
26}
27impl AsMut<TypeSet> for Info {
28    fn as_mut(&mut self) -> &mut TypeSet {
29        self.0.as_mut()
30    }
31}
32
33impl Info {
34    /// Returns the `local_addr` of a bound tcp listener, if such a
35    /// thing exists for this server
36    pub fn tcp_socket_addr(&self) -> Option<&SocketAddr> {
37        self.shared_state()
38    }
39
40    /// Returns the `local_addr` of a bound unix listener, if such a
41    /// thing exists for this server
42    #[cfg(unix)]
43    pub fn unix_socket_addr(&self) -> Option<&std::os::unix::net::SocketAddr> {
44        self.shared_state()
45    }
46
47    /// Borrow a type from the shared state [`TypeSet`] on this `Info`.
48    pub fn shared_state<T: Send + Sync + 'static>(&self) -> Option<&T> {
49        self.0.shared_state().get()
50    }
51
52    /// Insert a type into the shared state typeset, returning the previous value if any
53    pub fn insert_shared_state<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
54        self.0.shared_state_mut().insert(value)
55    }
56
57    /// Mutate a type in the shared state typeset
58    pub fn shared_state_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
59        self.0.shared_state_mut().get_mut()
60    }
61
62    /// Returns an [`Entry`] into the shared state typeset.
63    pub fn shared_state_entry<T: Send + Sync + 'static>(&mut self) -> Entry<'_, T> {
64        self.0.shared_state_mut().entry()
65    }
66
67    /// chainable interface to insert a type into the shared state typeset
68    #[must_use]
69    pub fn with_shared_state<T: Send + Sync + 'static>(mut self, value: T) -> Self {
70        self.insert_shared_state(value);
71        self
72    }
73
74    /// borrow the http config
75    pub fn config(&self) -> &HttpConfig {
76        self.0.config()
77    }
78
79    /// mutate the http config
80    pub fn config_mut(&mut self) -> &mut HttpConfig {
81        self.0.config_mut()
82    }
83
84    /// Borrow the [`Swansong`] graceful shutdown interface for this server
85    pub fn swansong(&self) -> &Swansong {
86        self.0.swansong()
87    }
88}