leptos_spin/
response_options.rs

1use std::sync::{Arc, RwLock};
2
3use spin_sdk::http::Headers;
4
5#[derive(Clone, Debug, Default)]
6pub struct ResponseOptions {
7    inner: Arc<RwLock<ResponseOptionsInner>>,
8}
9
10impl ResponseOptions {
11    pub fn status(&self) -> Option<u16> {
12        self.inner.read().unwrap().status
13    }
14    pub fn set_status(&self, status: u16) {
15        let mut inner = self.inner.write().unwrap();
16        inner.status = Some(status);
17    }
18    pub fn status_is_set(&self) -> bool {
19        let inner = self.inner.read().unwrap();
20        inner.status.is_some()
21    }
22    pub fn headers(&self) -> Headers {
23        self.inner.read().unwrap().headers.clone()
24    }
25    pub fn insert_header(&self, name: &str, value: impl Into<Vec<u8>>) {
26        let inner = self.inner.write().unwrap();
27        inner
28            .headers
29            .set(&name.to_string(), &[value.into()])
30            .expect("Failed to set header");
31    }
32    pub fn append_header(&self, name: &str, value: &[u8]) {
33        let inner = self.inner.write().unwrap();
34        inner
35            .headers
36            .append(&name.to_string(), &value.to_vec())
37            .expect("Failed to append header");
38    }
39    // Creates a ResponseOptions object with a default 200 status and no headers
40    // Useful for server functions
41    pub fn default_without_headers() -> Self {
42        Self {
43            inner: Arc::new(RwLock::new(ResponseOptionsInner::default_without_headers())),
44        }
45    }
46}
47
48#[derive(Debug)]
49struct ResponseOptionsInner {
50    status: Option<u16>,
51    headers: Headers,
52}
53
54impl Default for ResponseOptionsInner {
55    fn default() -> Self {
56        let headers = Headers::new();
57        headers
58            .append(
59                &"content-type".to_string(),
60                &"text/html".as_bytes().to_vec(),
61            )
62            .expect("Failed to append headers");
63        Self {
64            status: Default::default(),
65            headers,
66        }
67    }
68}
69
70impl ResponseOptionsInner {
71    // Creates a ResponseOptionsInner object with a default 200 status and no headers
72    // Useful for server functions
73    pub fn default_without_headers() -> Self {
74        Self {
75            status: Default::default(),
76            headers: Headers::new(),
77        }
78    }
79}