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
/// Byte-buffer types re-exported for use as request body extractors and as
/// response bodies.
pub use ;
use Parts;
use ;
use crate::;
/// An incoming HTTP request, carrying a [`Body`] by default.
pub type Request<T = Body> = Request;
/// A type that can be built from an incoming request.
///
/// A page or route handler may take a single `FromRequest` value as its request
/// body parameter, optionally alongside `cx: &Cx`. The built-in extractors
/// ([`Json`](crate::content::Json), [`Form`](crate::content::Form), [`Bytes`],
/// [`String`], [`Body`], and more) all implement this trait; implement it
/// yourself for request-specific parsing the built-ins don't cover.
///
/// Because the body is a stream that can only be read once, a handler may have
/// at most one `FromRequest` parameter. This is the request-side counterpart of
/// [`IntoResponse`](crate::response::IntoResponse).
///
/// An implementation that buffers the body should delegate the buffering to
/// [`Bytes`], which enforces the request's
/// [`body_limit`]; reading the body by hand bypasses that
/// limit.
///
/// # Examples
///
/// Implement it to parse a request in a way the built-ins don't cover. Here,
/// JSON whose body is verified against an `x-signature` header before it is
/// deserialized:
///
/// ```rust
/// # #[derive(serde::Deserialize)]
/// # struct CreateUser { name: String }
/// # fn verify_signature(_signature: &str, _bytes: &[u8]) -> topcoat::Result<()> { Ok(()) }
/// use serde::de::DeserializeOwned;
/// use topcoat::{
/// Result,
/// context::Cx,
/// router::{
/// Body,
/// error::bad_request,
/// request::{Bytes, FromRequest, headers},
/// route,
/// },
/// };
///
/// struct SignedJson<T>(T);
///
/// impl<T> FromRequest for SignedJson<T>
/// where
/// T: DeserializeOwned,
/// {
/// async fn from_request(cx: &Cx, body: Body) -> Result<Self> {
/// let signature = headers(cx)
/// .get("x-signature")
/// .and_then(|value| value.to_str().ok())
/// .ok_or_else(|| bad_request("missing x-signature header"))?;
///
/// let bytes = Bytes::from_request(cx, body).await?;
///
/// verify_signature(signature, &bytes)?;
///
/// Ok(Self(serde_json::from_slice(&bytes)?))
/// }
/// }
///
/// // Once implemented, use it like the built-in extractors:
/// #[route(POST "/api/signed")]
/// async fn signed(SignedJson(input): SignedJson<CreateUser>) -> Result<&'static str> {
/// let _ = input;
/// Ok("ok")
/// }
/// ```
/// Yields the request body unchanged, leaving it unbuffered for the handler to
/// read or forward itself.
/// Buffers the entire request body into memory, rejecting a body larger than
/// the request's [`body_limit`] with `413 Content Too Large`.
/// Buffers the entire request body into a mutable buffer.
/// Buffers the request body and decodes it as UTF-8, rejecting a non-UTF-8 body
/// with `400 Bad Request`.
/// Customizes the behavior of `Option<Self>` as a [`FromRequest`] extractor.
///
/// Implementing this trait lets `Option<Self>` be extracted from a request,
/// yielding `None` when the request carries no value for the extractor (for
/// example, a missing body) while still surfacing an error for values that are
/// present but malformed.
/// Makes any [`OptionalFromRequest`] extractor optional, yielding `None` when
/// the request carries no value of that kind while still surfacing an error for
/// a value that is present but malformed.
/// Returns the [`Parts`] of the current request.
///
/// Use this when you need access to multiple components of the request at
/// once. For individual fields, prefer the dedicated accessors
/// ([`method`], [`uri`], [`version`], [`headers`], [`extensions`]).
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::parts};
///
/// async fn log_request(cx: &Cx) {
/// let parts = parts(cx);
/// println!("{} {}", parts.method, parts.uri);
/// }
/// ```
/// Returns the HTTP [`Method`] of the current request.
///
/// [`Method`]: http::Method
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::method};
///
/// async fn is_post(cx: &Cx) -> bool {
/// method(cx) == http::Method::POST
/// }
/// ```
/// Returns the [`Uri`] of the current request.
///
/// [`Uri`]: http::Uri
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::uri};
///
/// async fn current_path(cx: &Cx) -> &str {
/// uri(cx).path()
/// }
/// ```
/// The URI a rewritten request originally arrived with, stored on the request
/// context of every dispatch reached through a rewrite.
pub Uri);
/// Returns the [`Uri`] the client actually requested, before any rewrite.
///
/// A handler reached through a [`rewrite`](crate::error::rewrite) sees the
/// rewritten URI in [`uri`]; this accessor returns the URI the request
/// arrived with, for example to render a form that posts back to the visible
/// URL. For a request that was never rewritten the two are the same.
///
/// [`Uri`]: http::Uri
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::original_uri};
///
/// async fn form_action(cx: &Cx) -> String {
/// original_uri(cx).path().to_owned()
/// }
/// ```
/// Returns the HTTP [`Version`] of the current request.
///
/// [`Version`]: http::Version
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::version};
///
/// async fn is_http2(cx: &Cx) -> bool {
/// *version(cx) == http::Version::HTTP_2
/// }
/// ```
/// Returns the [`HeaderMap`] of the current request.
///
/// [`HeaderMap`]: http::HeaderMap
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::headers};
///
/// async fn user_agent(cx: &Cx) -> Option<&str> {
/// headers(cx).get("user-agent")?.to_str().ok()
/// }
/// ```
/// Returns the `Content-Type` header of the current request as a string slice,
/// or [`None`] when it is absent or not valid UTF-8.
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::content_type};
///
/// async fn is_json(cx: &Cx) -> bool {
/// content_type(cx).is_some_and(|value| value.starts_with("application/json"))
/// }
/// ```
/// Returns the [`Extensions`] of the current request.
///
/// Extensions carry typed values attached to the request, typically by
/// middleware running before the handler.
///
/// [`Extensions`]: http::Extensions
///
/// # Examples
///
/// ```rust
/// use topcoat::{context::Cx, router::request::extensions};
///
/// struct RequestId(String);
///
/// async fn request_id(cx: &Cx) -> Option<&str> {
/// extensions(cx).get::<RequestId>().map(|id| id.0.as_str())
/// }
/// ```