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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::sync::{Arc, RwLock};

use spin_sdk::http::Headers;

#[derive(Clone, Debug, Default)]
pub struct ResponseOptions {
    inner: Arc<RwLock<ResponseOptionsInner>>,
}

impl ResponseOptions {
    pub fn status(&self) -> Option<u16> {
        self.inner.read().unwrap().status
    }
    pub fn set_status(&self, status: u16) {
        let mut inner = self.inner.write().unwrap();
        inner.status = Some(status);
    }

    pub fn headers(&self) -> Headers {
        self.inner.read().unwrap().headers.clone()
    }
    pub fn insert_header(&self, name: &str, value: impl Into<Vec<u8>>) {
        let inner = self.inner.write().unwrap();
        inner.headers.set(name, &[value.into()]);
    }
    pub fn append_header(&self, name: &str, value: &[u8]) {
        let inner = self.inner.write().unwrap();
        inner.headers.append(name, value);
    }
    // Creates a ResponseOptions object with a default 200 status and no headers
    // Useful for server functions
    pub fn default_without_headers() -> Self {
        Self{
            inner: Arc::new(RwLock::new(ResponseOptionsInner::default_without_headers())),
        }
    }
}

#[derive(Debug)]
struct ResponseOptionsInner {
    status: Option<u16>,
    headers: Headers,
}

impl Default for ResponseOptionsInner {
    fn default() -> Self {
        Self {
            status: Default::default(),
            headers: Headers::new(&[("content-type".to_owned(), "text/html".into())]),
        }
    }
}

impl ResponseOptionsInner{
    // Creates a ResponseOptionsInner object with a default 200 status and no headers
    // Useful for server functions
    pub fn default_without_headers() -> Self{
        Self {
            status: Default::default(),
            headers: Headers::new(&[]),
        }
    }
}