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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use std::fmt;
use std::fmt::{Display, Formatter};

use bytes::Bytes;
#[cfg(feature = "cookie")]
use cookie::{Cookie, CookieJar};
use http::{Extensions, Version};
use http_body::{Body, SizeHint};
use serde::Serialize;
use serde_json::Value;

use crate::core::res_body::{full, ResBody};
use crate::headers::{ContentType, Header, HeaderMap, HeaderMapExt};
use crate::{header, Configs, Result, SilentError, StatusCode};

/// 响应体
/// ```
/// use silent::Response;
/// let req = Response::empty();
/// ```
pub struct Response<B: Body = ResBody> {
    /// The HTTP status code.
    pub(crate) status: StatusCode,
    /// The HTTP version.
    pub(crate) version: Version,
    /// The HTTP headers.
    pub(crate) headers: HeaderMap,
    pub(crate) body: B,
    #[cfg(feature = "cookie")]
    pub(crate) cookies: CookieJar,
    pub(crate) extensions: Extensions,
    pub(crate) configs: Configs,
}

impl fmt::Debug for Response {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        writeln!(f, "{:?} {}\n{:?}", self.version, self.status, self.headers)
    }
}

impl Display for Response {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl Response {
    /// 创建空响应体
    pub fn empty() -> Self {
        Self {
            status: StatusCode::OK,
            headers: HeaderMap::new(),
            version: Version::default(),
            body: ResBody::None,
            #[cfg(feature = "cookie")]
            cookies: CookieJar::default(),
            extensions: Extensions::default(),
            configs: Configs::default(),
        }
    }
    #[inline]
    /// 设置响应重定向
    pub fn redirect(url: &str) -> Result<Self> {
        let mut res = Self::empty();
        res.status = StatusCode::MOVED_PERMANENTLY;
        res.headers.insert(
            header::LOCATION,
            url.parse().map_err(|e| {
                SilentError::business_error(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("redirect error: {}", e),
                )
            })?,
        );
        Ok(res)
    }
}

impl<B: Body> Response<B> {
    /// 设置响应状态
    #[inline]
    pub fn set_status(&mut self, status: StatusCode) {
        self.status = status;
    }
    /// 包含响应状态
    #[inline]
    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }
    /// 设置响应body
    #[inline]
    pub fn set_body(&mut self, body: B) {
        self.body = body;
    }
    /// 包含响应body
    #[inline]
    pub fn with_body(mut self, body: B) -> Self {
        self.body = body;
        self
    }
    /// 获取响应体
    #[inline]
    pub fn body(&self) -> &B {
        &self.body
    }
    /// 设置响应header
    #[inline]
    pub fn set_header(&mut self, key: header::HeaderName, value: header::HeaderValue) {
        self.headers.insert(key, value);
    }
    /// 包含响应header
    #[inline]
    pub fn with_header(mut self, key: header::HeaderName, value: header::HeaderValue) -> Self {
        self.headers.insert(key, value);
        self
    }
    #[inline]
    /// 获取extensions
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }
    #[inline]
    /// 获取extensions_mut
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }

    /// 获取配置
    #[inline]
    pub fn get_config<T: Send + Sync + 'static>(&self) -> Result<&T> {
        self.configs.get::<T>().ok_or(SilentError::ConfigNotFound)
    }

    /// 获取配置(Uncheck)
    #[inline]
    pub fn get_config_uncheck<T: Send + Sync + 'static>(&self) -> &T {
        self.configs.get::<T>().unwrap()
    }

    /// 获取全局配置
    #[inline]
    pub fn configs(&self) -> &Configs {
        &self.configs
    }

    /// 获取可变全局配置
    #[inline]
    pub fn configs_mut(&mut self) -> &mut Configs {
        &mut self.configs
    }
    #[inline]
    /// 设置响应header
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    #[inline]
    /// 设置响应header
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.headers
    }
    #[inline]
    /// 获取响应体长度
    pub fn content_length(&self) -> SizeHint {
        self.body.size_hint()
    }
    #[inline]
    /// 设置响应header
    pub fn set_typed_header<H>(&mut self, header: H)
    where
        H: Header,
    {
        self.headers.typed_insert(header);
    }
    #[inline]
    /// 包含响应header
    pub fn with_typed_header<H>(mut self, header: H) -> Self
    where
        H: Header,
    {
        self.headers.typed_insert(header);
        self
    }

    #[cfg(feature = "cookie")]
    /// Get `CookieJar` reference.
    #[inline]
    pub fn cookies(&self) -> &CookieJar {
        &self.cookies
    }
    #[cfg(feature = "cookie")]
    /// Get `CookieJar` mutable reference.
    #[inline]
    pub fn cookies_mut(&mut self) -> &mut CookieJar {
        &mut self.cookies
    }
    #[cfg(feature = "cookie")]
    /// Get `Cookie` from cookies.
    #[inline]
    pub fn cookie<T>(&self, name: T) -> Option<&Cookie<'static>>
    where
        T: AsRef<str>,
    {
        self.cookies.get(name.as_ref())
    }

    #[cfg(feature = "cookie")]
    /// move response to from another response
    pub fn copy_from_response(&mut self, res: Response<B>) {
        self.headers.extend(res.headers);
        res.cookies.delta().for_each(|cookie| {
            self.cookies.add(cookie.clone());
        });
        self.status = res.status;
        self.extensions.extend(res.extensions);
        self.set_body(res.body);
    }

    #[cfg(not(feature = "cookie"))]
    /// move response to from another response
    pub fn copy_from_response(&mut self, res: Response<B>) {
        self.headers.extend(res.headers);
        self.status = res.status;
        self.extensions.extend(res.extensions);
        self.set_body(res.body);
    }
}

impl<S: Serialize> From<S> for Response {
    fn from(value: S) -> Self {
        let mut res = Response::empty();
        let result: Bytes = match serde_json::to_value(&value).unwrap() {
            Value::String(value) => {
                if value.contains("html") {
                    res.set_typed_header(ContentType::html());
                } else {
                    res.set_typed_header(ContentType::text_utf8());
                }
                value.into_bytes().into()
            }
            _ => {
                res.set_typed_header(ContentType::json());
                serde_json::to_vec(&value).unwrap().into()
            }
        };
        res.set_body(full(result));
        res
    }
}