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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! The header module of roa.
//! This module provides a Request/Response extension `FriendlyHeaders`.
//!
//! ### When should we use it?
//!
//! You can straightly use raw `http::header::HeaderMap` in roa,
//! but you have to transfer value type between HeaderValue and string then
//! deal with other errors(not `roa::Error`) by yourself.
//! ```rust
//! use roa::{Context, Result, Error};
//! use roa::http::header::{ORIGIN, CONTENT_TYPE};
//! use roa::http::StatusCode;
//!
//! async fn get(mut ctx: Context<()>) -> Result {
//!     if let Some(value) = ctx.req().headers.get(ORIGIN) {
//!         // handle `ToStrError`
//!         let origin = value.to_str().map_err(|_err| Error::new(StatusCode::BAD_REQUEST, "", true))?;
//!         println!("origin: {}", origin);
//!     }
//!     // handle `InvalidHeaderValue`
//!     ctx.resp_mut()
//!        .headers
//!        .insert(
//!            CONTENT_TYPE,
//!            "text/plain".parse().map_err(|_err| Error::new(StatusCode::BAD_REQUEST, "", true))?
//!        );
//!     Ok(())
//! }
//! ```
//!
//! Dealing with errors is necessary but sometimes can be annoying
//!
//! If you are finding some simpler methods to deal with header value, `FriendlyHeaders` is suit for you.
//!
//! ```rust
//! use roa::{Context, Result};
//! use roa::http::header::{ORIGIN, CONTENT_TYPE};
//! use roa::http::StatusCode;
//! use roa::header::FriendlyHeaders;
//!
//! async fn get(mut ctx: Context<()>) -> Result {
//!     println!("origin: {}", ctx.req().must_get(ORIGIN)?);
//!     ctx.resp_mut()
//!        .insert(CONTENT_TYPE, "text/plain")?;
//!     Ok(())
//! }
//! ```
use crate::http::header::{
    AsHeaderName, HeaderMap, HeaderValue, IntoHeaderName, ToStrError,
};
use crate::http::StatusCode;
use crate::{Error, Request, Response, Result};
use std::convert::TryInto;
use std::fmt::Display;

/// Handle errors occur in converting from other value to header value.
fn handle_invalid_header_value(err: impl Display) -> Error {
    Error::new(
        StatusCode::INTERNAL_SERVER_ERROR,
        format!("{}\nInvalid header value", err),
        false,
    )
}

/// A Request/Response extension.
pub trait FriendlyHeaders {
    /// StatusCode of general error.
    ///
    /// 400 BAD REQUEST for Request,
    /// 500 INTERNAL SERVER ERROR for Response.
    const GENERAL_ERROR_CODE: StatusCode;

    /// If general errors should be exposed.
    ///
    /// true for Request,
    /// false for Response.
    const GENERAL_ERROR_EXPOSE: bool;

    /// Get immutable reference of raw header map.
    fn raw_header_map(&self) -> &HeaderMap<HeaderValue>;

    /// Get mutable reference of raw header map.
    fn raw_mut_header_map(&mut self) -> &mut HeaderMap<HeaderValue>;

    /// Deal with `ToStrError`, usually invoked when a header value is gotten,
    /// then fails to be transferred to string.
    /// Throw `Self::GENERAL_ERROR_CODE`.
    #[inline]
    fn handle_to_str_error(err: ToStrError, value: &HeaderValue) -> Error {
        Error::new(
            Self::GENERAL_ERROR_CODE,
            format!("{}\n{:?} is not a valid string", err, value),
            Self::GENERAL_ERROR_EXPOSE,
        )
    }

    /// Deal with None, usually invoked when a header value is not gotten.
    /// Throw `Self::GENERAL_ERROR_CODE`.
    #[inline]
    fn handle_none<K>(key: K) -> Error
    where
        K: Display,
    {
        Error::new(
            Self::GENERAL_ERROR_CODE,
            format!("header `{}` is required", key),
            Self::GENERAL_ERROR_EXPOSE,
        )
    }

    /// Try to get a header value, return None if not exists.
    /// Return Some(Err) if fails to string.
    ///
    /// ### Example
    ///
    /// ```rust
    /// use roa::{Context, Result};
    /// use roa::http::header::{ORIGIN, CONTENT_TYPE};
    /// use roa::http::StatusCode;
    /// use roa::header::FriendlyHeaders;
    ///
    /// async fn get(ctx: Context<()>) -> Result {
    ///     if let Some(value) = ctx.req().get(ORIGIN) {
    ///         println!("origin: {}", value?);     
    ///     }   
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    fn get<K>(&self, key: K) -> Option<Result<&str>>
    where
        K: AsHeaderName,
    {
        self.raw_header_map().get(key).map(|value| {
            value
                .to_str()
                .map_err(|err| Self::handle_to_str_error(err, value))
        })
    }

    /// Get a header value.
    /// Return Err if not exists or fails to string.
    /// ### Example
    ///
    /// ```rust
    /// use roa::{Context, Result};
    /// use roa::http::header::{ORIGIN, CONTENT_TYPE};
    /// use roa::http::StatusCode;
    /// use roa::header::FriendlyHeaders;
    ///
    /// async fn get(ctx: Context<()>) -> Result {
    ///     println!("origin: {}", ctx.req().must_get(ORIGIN)?);     
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    fn must_get<K>(&self, key: K) -> Result<&str>
    where
        K: AsRef<str>,
    {
        match self.get(key.as_ref()) {
            Some(result) => result,
            None => Err(Self::handle_none(key.as_ref())),
        }
    }

    /// Get all header value with the same header name.
    /// Return Err if one of them fails to string.
    ///
    /// ### Example
    ///
    /// ```rust
    /// use roa::{Context, Result};
    /// use roa::http::header::{ORIGIN, CONTENT_TYPE};
    /// use roa::http::StatusCode;
    /// use roa::header::FriendlyHeaders;
    ///
    /// async fn get(ctx: Context<()>) -> Result {
    ///     for value in ctx.req().get_all(ORIGIN)?.into_iter() {
    ///         println!("origin: {}", value);
    ///     }
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    fn get_all<K>(&self, key: K) -> Result<Vec<&str>>
    where
        K: AsHeaderName,
    {
        let mut ret = Vec::new();
        for value in self.raw_header_map().get_all(key).iter() {
            ret.push(
                value
                    .to_str()
                    .map_err(|err| Self::handle_to_str_error(err, value))?,
            );
        }
        Ok(ret)
    }

    /// Insert a header pair.
    ///
    /// - Return `Err(500 INTERNAL SERVER ERROR)` if value fails to header value.
    /// - Return `Ok(Some(old_value))` if header name already exists.
    ///
    /// ### Example
    ///
    /// ```rust
    /// use roa::{Context, Result};
    /// use roa::http::header::{ORIGIN, CONTENT_TYPE};
    /// use roa::http::StatusCode;
    /// use roa::header::FriendlyHeaders;
    ///
    /// async fn get(mut ctx: Context<()>) -> Result {
    ///     ctx.resp_mut().insert(CONTENT_TYPE, "text/plain")?;   
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    fn insert<K, V>(&mut self, key: K, val: V) -> Result<Option<String>>
    where
        K: IntoHeaderName,
        V: TryInto<HeaderValue>,
        V::Error: Display,
    {
        let old_value = self
            .raw_mut_header_map()
            .insert(key, val.try_into().map_err(handle_invalid_header_value)?);
        Ok(match old_value {
            Some(value) => Some(
                value
                    .to_str()
                    .map(ToString::to_string)
                    .map_err(|err| Self::handle_to_str_error(err, &value))?,
            ),
            None => None,
        })
    }

    /// Append a header pair.
    ///
    /// - Return `Err(500 INTERNAL SERVER ERROR)` if value fails to header value.
    /// - Return `Ok(true)` if header name already exists.
    ///
    /// ### Example
    ///
    /// ```rust
    /// use roa::{Context, Result};
    /// use roa::http::header::SET_COOKIE;
    /// use roa::http::StatusCode;
    /// use roa::header::FriendlyHeaders;
    ///
    /// async fn get(mut ctx: Context<()>) -> Result {
    ///     ctx.resp_mut().append(SET_COOKIE, "this is a cookie")?;   
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    fn append<K, V>(&mut self, key: K, val: V) -> Result<bool>
    where
        K: IntoHeaderName,
        V: TryInto<HeaderValue>,
        V::Error: Display,
    {
        Ok(self
            .raw_mut_header_map()
            .append(key, val.try_into().map_err(handle_invalid_header_value)?))
    }
}

impl FriendlyHeaders for Request {
    const GENERAL_ERROR_CODE: StatusCode = StatusCode::BAD_REQUEST;
    const GENERAL_ERROR_EXPOSE: bool = true;

    #[inline]
    fn raw_header_map(&self) -> &HeaderMap<HeaderValue> {
        &self.headers
    }

    #[inline]
    fn raw_mut_header_map(&mut self) -> &mut HeaderMap<HeaderValue> {
        &mut self.headers
    }
}

impl FriendlyHeaders for Response {
    const GENERAL_ERROR_CODE: StatusCode = StatusCode::INTERNAL_SERVER_ERROR;
    const GENERAL_ERROR_EXPOSE: bool = false;

    #[inline]
    fn raw_header_map(&self) -> &HeaderMap<HeaderValue> {
        &self.headers
    }

    #[inline]
    fn raw_mut_header_map(&mut self) -> &mut HeaderMap<HeaderValue> {
        &mut self.headers
    }
}

#[cfg(test)]
mod tests {
    use crate::http::header::CONTENT_TYPE;
    use crate::http::{HeaderValue, StatusCode};
    use crate::preload::*;
    use crate::Request;
    use mime::TEXT_HTML;

    #[test]
    fn request_raw_mut_header_map() {
        let mut request = Request::default();
        request
            .raw_mut_header_map()
            .insert(CONTENT_TYPE, TEXT_HTML.as_ref().parse().unwrap());
        let content_type = request.must_get(CONTENT_TYPE).unwrap();
        assert_eq!(TEXT_HTML.as_ref(), content_type);
    }

    #[test]
    fn request_get_non_string() {
        let mut request = Request::default();
        request.raw_mut_header_map().insert(
            CONTENT_TYPE,
            HeaderValue::from_bytes([230].as_ref()).unwrap(),
        );
        let ret = request.get(CONTENT_TYPE).unwrap();
        assert!(ret.is_err());
        let status = ret.unwrap_err();
        assert_eq!(StatusCode::BAD_REQUEST, status.status_code);
        assert!(status.message.ends_with("is not a valid string"));
    }

    #[test]
    fn must_get_fails() {
        let request = Request::default();
        let ret = request.must_get(CONTENT_TYPE);
        assert!(ret.is_err());
        let status = ret.unwrap_err();
        assert_eq!(StatusCode::BAD_REQUEST, status.status_code);
        assert_eq!("header `content-type` is required", status.message);
    }

    #[test]
    fn request_get_all_non_string() {
        let mut request = Request::default();
        request.raw_mut_header_map().insert(
            CONTENT_TYPE,
            HeaderValue::from_bytes([230].as_ref()).unwrap(),
        );
        let ret = request.get_all(CONTENT_TYPE);
        assert!(ret.is_err());
        let status = ret.unwrap_err();
        assert_eq!(StatusCode::BAD_REQUEST, status.status_code);
        assert!(status.message.ends_with("is not a valid string"));
    }

    #[test]
    fn request_get_all() -> Result<(), Box<dyn std::error::Error>> {
        let mut request = Request::default();
        request.append(CONTENT_TYPE, "text/html")?;
        request.append(CONTENT_TYPE, "text/plain")?;
        let ret = request.get_all(CONTENT_TYPE)?;
        assert_eq!("text/html", ret[0]);
        assert_eq!("text/plain", ret[1]);
        Ok(())
    }

    #[test]
    fn insert() -> Result<(), Box<dyn std::error::Error>> {
        let mut request = Request::default();
        request.insert(CONTENT_TYPE, "text/html")?;
        assert_eq!("text/html", request.must_get(CONTENT_TYPE)?);
        let old_data = request.insert(CONTENT_TYPE, "text/plain")?.unwrap();
        assert_eq!("text/html", old_data);
        assert_eq!("text/plain", request.must_get(CONTENT_TYPE)?);
        Ok(())
    }

    #[test]
    fn insert_fail() -> Result<(), Box<dyn std::error::Error>> {
        let mut request = Request::default();
        let ret = request.insert(CONTENT_TYPE, "\r\n");
        assert!(ret.is_err());
        let status = ret.unwrap_err();
        assert_eq!(StatusCode::INTERNAL_SERVER_ERROR, status.status_code);
        assert!(status.message.ends_with("Invalid header value"));
        Ok(())
    }

    #[test]
    fn append_fail() -> Result<(), Box<dyn std::error::Error>> {
        let mut request = Request::default();
        let ret = request.append(CONTENT_TYPE, "\r\n");
        assert!(ret.is_err());
        let status = ret.unwrap_err();
        assert_eq!(StatusCode::INTERNAL_SERVER_ERROR, status.status_code);
        assert!(status.message.ends_with("Invalid header value"));
        Ok(())
    }
}