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
use http::{HeaderMap, Method, Uri, Version};
use http_service::Body;
use route_recognizer::Params;
use serde::Deserialize;
use async_std::io::{self, prelude::*};
use async_std::task::{Context, Poll};
use std::pin::Pin;
use std::{str::FromStr, sync::Arc};
pin_project_lite::pin_project! {
#[derive(Debug)]
pub struct Request<State> {
state: Arc<State>,
#[pin]
request: http_service::Request,
route_params: Params,
}
}
impl<State> Request<State> {
pub(crate) fn new(
state: Arc<State>,
request: http::Request<Body>,
route_params: Params,
) -> Request<State> {
Request {
state,
request,
route_params,
}
}
pub fn method(&self) -> &Method {
self.request.method()
}
pub fn uri(&self) -> &Uri {
self.request.uri()
}
pub fn version(&self) -> Version {
self.request.version()
}
pub fn headers(&self) -> &HeaderMap {
self.request.headers()
}
pub fn header(&self, key: &'static str) -> Option<&'_ str> {
self.request.headers().get(key).map(|h| h.to_str().unwrap())
}
pub fn set_header(mut self, key: &'static str, value: impl AsRef<str>) -> Self {
let value = value.as_ref().to_owned();
self.request
.headers_mut()
.insert(key, value.parse().unwrap());
self
}
pub fn local<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.request.extensions().get()
}
pub fn set_local<T: Send + Sync + 'static>(mut self, val: T) -> Self {
self.request.extensions_mut().insert(val);
self
}
pub fn state(&self) -> &State {
&self.state
}
pub fn param<T: FromStr>(&self, key: &str) -> Result<T, T::Err> {
self.route_params.find(key).unwrap().parse()
}
pub async fn body_bytes(&mut self) -> std::io::Result<Vec<u8>> {
let mut buf = Vec::with_capacity(1024);
self.request.body_mut().read_to_end(&mut buf).await?;
Ok(buf)
}
pub async fn body_string(&mut self) -> std::io::Result<String> {
let body_bytes = self.body_bytes().await?;
Ok(String::from_utf8(body_bytes).map_err(|_| std::io::ErrorKind::InvalidData)?)
}
pub async fn body_json<T: serde::de::DeserializeOwned>(&mut self) -> std::io::Result<T> {
let body_bytes = self.body_bytes().await?;
Ok(serde_json::from_slice(&body_bytes).map_err(|_| std::io::ErrorKind::InvalidData)?)
}
pub fn query<'de, T: Deserialize<'de>>(&'de self) -> Result<T, crate::Error> {
let query = self.uri().query();
if query.is_none() {
return Err(crate::Error::from(http::StatusCode::BAD_REQUEST));
}
Ok(serde_qs::from_str(query.unwrap())
.map_err(|_| crate::Error::from(http::StatusCode::BAD_REQUEST))?)
}
pub async fn body_form<T: serde::de::DeserializeOwned>(&mut self) -> io::Result<T> {
let body = self
.body_bytes()
.await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
let res = serde_qs::from_bytes(&body).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("could not decode form: {}", e),
)
})?;
Ok(res)
}
}
impl<State> Read for Request<State> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let mut this = self.project();
Pin::new(this.request.body_mut()).poll_read(cx, buf)
}
}