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
use lambda_http::{
http::{
header::{HeaderValue, IntoHeaderName},
StatusCode,
},
Body,
};
use crate::{error, handler::Handler};
pub type Middleware<E = error::Error> = Box<dyn Fn(Handler<E>) -> Handler<E>>;
pub fn header<E: 'static, N, V>(header_name: N, header_value: V) -> Middleware<E>
where
N: IntoHeaderName + Copy + 'static,
V: Into<String> + Copy + 'static,
{
Box::new(move |handler| {
Box::new(move |request, context| {
let mut response = handler(request, context)?;
if let Ok(value) = HeaderValue::from_str(header_value.into().as_str()) {
response.headers_mut().insert(header_name, value);
}
Ok(response)
})
})
}
pub fn status<E: 'static>(code: StatusCode) -> Middleware<E> {
Box::new(move |handler| {
Box::new(move |request, context| {
let mut response = handler(request, context)?;
*response.status_mut() = code;
Ok(response)
})
})
}
pub fn body<E: 'static, B>(body: B) -> Middleware<E>
where
B: Into<Body> + Copy + 'static,
{
Box::new(move |handler| {
Box::new(move |request, context| {
let mut response = handler(request, context)?;
*response.body_mut() = body.into();
Ok(response)
})
})
}
#[cfg(test)]
mod tests {
use std::fmt::Debug;
use lambda_http::{http::StatusCode, Body, Request, Response};
use lambda_runtime::Context;
use crate::handler::{default_handler, WrappingHandler};
use super::*;
fn handler_resp<E: Debug>(handler: Handler<E>) -> Response<Body> {
let request = Request::default();
let context = Context::default();
handler(request, context).unwrap()
}
#[test]
fn test_header() {
let handler = default_handler::<error::Error>()
.wrap_with(header("x-foo", "bar"))
.handler();
let resp = handler_resp(handler);
assert_eq!(
resp.headers().get("x-foo"),
Some(&HeaderValue::from_static("bar"))
);
}
#[test]
fn test_status() {
let handler = default_handler::<error::Error>()
.wrap_with(status(StatusCode::CREATED))
.handler();
let resp = handler_resp(handler);
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[test]
fn test_body() {
let handler = default_handler::<error::Error>()
.wrap_with(body("foo"))
.handler();
let resp = handler_resp(handler);
assert_eq!(*resp.body(), Body::Text("foo".to_string()));
}
}