routerify 2.0.0

A lightweight, idiomatic, composable and modular router implementation with middleware support for the Rust HTTP library hyper.rs.
Documentation
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
401
402
403
404
405
406
407
408
409
410
411
412
use self::support::{into_text, serve};
use hyper::{Body, Client, Request, Response, StatusCode};
use routerify::prelude::RequestExt;
use routerify::{Middleware, RequestInfo, RouteError, Router};
use std::io;
use std::sync::{Arc, Mutex};

mod support;

#[tokio::test]
async fn can_perform_simple_get_request() {
    const RESPONSE_TEXT: &str = "Hello world";
    let router: Router<Body, routerify::Error> = Router::builder()
        .get("/", |_| async move { Ok(Response::new(RESPONSE_TEXT.into())) })
        .err_handler(|_: RouteError| async move { todo!() })
        .build()
        .unwrap();
    let serve = serve(router).await;
    let resp = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let resp = into_text(resp.into_body()).await;
    assert_eq!(resp, RESPONSE_TEXT.to_owned());
    serve.shutdown();
}

#[tokio::test]
async fn can_perform_simple_get_request_boxed_error() {
    const RESPONSE_TEXT: &str = "Hello world";
    type BoxedError = Box<dyn std::error::Error + Sync + Send + 'static>;
    let router: Router<Body, BoxedError> = Router::builder()
        .get("/", |_| async move { Ok(Response::new(RESPONSE_TEXT.into())) })
        .err_handler(|_: RouteError| async move { todo!() })
        .build()
        .unwrap();
    let serve = serve(router).await;
    let resp = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let resp = into_text(resp.into_body()).await;
    assert_eq!(resp, RESPONSE_TEXT.to_owned());
    serve.shutdown();
}

#[tokio::test]
async fn can_respond_with_data_from_scope_state() {
    // Creating two modules containing separate state and routes which expose that state directly...
    mod service1 {
        use super::*;
        struct State {
            count: Arc<Mutex<u8>>,
        }
        async fn list(req: Request<Body>) -> Result<Response<Body>, io::Error> {
            let count = req.data::<State>().unwrap().count.lock().unwrap();
            Ok(Response::new(Body::from(format!("{}", count))))
        }
        pub fn router() -> Router<Body, io::Error> {
            let state = State {
                count: Arc::new(Mutex::new(1)),
            };
            Router::builder().data(state).get("/", list).build().unwrap()
        }
    }

    mod service2 {
        use super::*;
        struct State {
            count: Arc<Mutex<u8>>,
        }
        async fn list(req: Request<Body>) -> Result<Response<Body>, io::Error> {
            let count = req.data::<State>().unwrap().count.lock().unwrap();
            Ok(Response::new(Body::from(format!("{}", count))))
        }
        pub fn router() -> Router<Body, io::Error> {
            let state = State {
                count: Arc::new(Mutex::new(2)),
            };
            Router::builder().data(state).get("/", list).build().unwrap()
        }
    }

    let router = Router::builder()
        .scope(
            "/v1",
            Router::builder()
                .scope("/service1", service1::router())
                .scope("/service2", service2::router())
                .build()
                .unwrap(),
        )
        .build()
        .unwrap();
    let serve = serve(router).await;

    // Ensure response contains service1's unique data.
    let resp = Client::new()
        .request(serve.new_request("GET", "/v1/service1").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(200, resp.status().as_u16());
    assert_eq!("1", into_text(resp.into_body()).await);

    // Ensure response contains service2's unique data.
    let resp = Client::new()
        .request(serve.new_request("GET", "/v1/service2").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(200, resp.status().as_u16());
    assert_eq!(into_text(resp.into_body()).await, "2");

    serve.shutdown();
}

#[tokio::test]
async fn can_propagate_request_context() {
    use std::io;
    #[derive(Debug, Clone, PartialEq)]
    struct Id(u32);

    let before = |req: Request<Body>| async move {
        req.set_context(Id(42));
        Ok(req)
    };

    let index = |req: Request<Body>| async move {
        // Check `id` from `before()`.
        let id = req.context::<Id>().unwrap();
        assert_eq!(id, Id(42));

        // Check that non-existent context value is None.
        let none = req.context::<u64>();
        assert!(none.is_none());

        // Add a String value to the context.
        req.set_context("index".to_string());

        // Trigger this error in order to invoke
        // the error handler.
        Err(io::Error::new(io::ErrorKind::AddrInUse, "bogus error"))
    };

    let error_handler = |_err, req_info: RequestInfo| async move {
        // Check `id` from `before()`.
        let id = req_info.context::<Id>().unwrap();
        assert_eq!(id, Id(42));

        // Check String from `index()`.
        let name = req_info.context::<String>().unwrap();
        assert_eq!(name, "index");

        Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body(Body::from("Something went wrong"))
            .unwrap()
    };

    let after = |res, req_info: RequestInfo| async move {
        // Check `id` from `before()`.
        let id = req_info.context::<Id>().unwrap();
        assert_eq!(id, Id(42));

        // Check String from `index()`.
        let name = req_info.context::<String>().unwrap();
        assert_eq!(name, "index");

        Ok(res)
    };

    let router: Router<Body, std::io::Error> = Router::builder()
        .middleware(Middleware::pre(before))
        .middleware(Middleware::post_with_info(after))
        .err_handler_with_info(error_handler)
        .get("/", index)
        .build()
        .unwrap();
    let serve = serve(router).await;
    let _ = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    serve.shutdown();
}

#[tokio::test]
async fn can_extract_path_params() {
    const RESPONSE_TEXT: &str = "Hello world";
    let router: Router<Body, routerify::Error> = Router::builder()
        .get("/api/:first/plus/:second", |req| async move {
            let first = req.param("first").unwrap();
            let second = req.param("second").unwrap();
            assert_eq!(first, "40");
            assert_eq!(second, "2");
            Ok(Response::new(RESPONSE_TEXT.into()))
        })
        .build()
        .unwrap();
    let serve = serve(router).await;
    let resp = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/api/40/plus/2", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let resp = into_text(resp.into_body()).await;
    assert_eq!(resp, RESPONSE_TEXT.to_owned());
    serve.shutdown();
}

#[tokio::test]
async fn do_not_execute_scoped_middleware_for_unscoped_path() {
    let api_router: Router<Body, routerify::Error> = Router::builder()
        .middleware(Middleware::pre(|_| async { panic!("should not be executed") }))
        .middleware(Middleware::post(|_| async { panic!("should not be executed") }))
        .get("/api/todo", |_| async { Ok(Response::new("".into())) })
        .build()
        .unwrap();

    let router: Router<Body, routerify::Error> = Router::builder()
        .get("/", |_| async { Ok(Response::new("".into())) })
        .scope("/api", api_router)
        .get("/api/login", |_| async { Ok(Response::new("".into())) })
        .build()
        .unwrap();

    let serve = serve(router).await;
    let _ = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/api/login", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    serve.shutdown();
}

#[tokio::test]
async fn execute_scoped_middleware_when_no_unscoped_match() {
    use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
    use std::sync::Arc;

    struct ExecPre(AtomicBool);
    struct ExecPost(AtomicBool);

    let executed_pre = Arc::new(ExecPre(AtomicBool::new(false)));
    let executed_post = Arc::new(ExecPost(AtomicBool::new(false)));

    // Record the execution of pre and post middleware.
    let api_router: Router<Body, routerify::Error> = Router::builder()
        .middleware(Middleware::pre(|req| async {
            let pre = req.data::<Arc<ExecPre>>().unwrap();
            pre.0.store(true, SeqCst);
            Ok(req)
        }))
        .middleware(Middleware::pre(|req| async {
            let post = req.data::<Arc<ExecPost>>().unwrap();
            post.0.store(true, SeqCst);
            Ok(req)
        }))
        .get("/api/todo", |_| async { Ok(Response::new("".into())) })
        .build()
        .unwrap();

    let router: Router<Body, routerify::Error> = Router::builder()
        .data(executed_pre.clone())
        .data(executed_post.clone())
        .get("/", |_| async { Ok(Response::new("".into())) })
        .scope("/api", api_router)
        .get("/api/login", |_| async { Ok(Response::new("".into())) })
        .build()
        .unwrap();

    let serve = serve(router).await;
    let _ = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/api/nomatch", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert!(executed_pre.0.load(SeqCst));
    assert!(executed_post.0.load(SeqCst));

    serve.shutdown();
}

#[tokio::test]
async fn can_handle_custom_errors() {
    #[derive(Debug)]
    enum ApiError {
        Generic(String),
    }
    impl std::error::Error for ApiError {}
    impl std::fmt::Display for ApiError {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            match self {
                ApiError::Generic(s) => write!(f, "Generic: {}", s),
            }
        }
    }

    const RESPONSE_TEXT: &str = "Something went wrong!";
    let router: Router<Body, ApiError> = Router::builder()
        .get("/", |_| async move { Err(ApiError::Generic(RESPONSE_TEXT.into())) })
        .err_handler(|err: RouteError| async move {
            let api_err = err.downcast::<ApiError>().unwrap();
            match api_err.as_ref() {
                ApiError::Generic(s) => Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::from(s.to_string()))
                    .unwrap(),
            }
        })
        .build()
        .unwrap();
    let serve = serve(router).await;

    let resp = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}/", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    let resp = into_text(resp.into_body()).await;
    assert_eq!(resp, RESPONSE_TEXT.to_owned());
    serve.shutdown();
}

#[tokio::test]
async fn can_handle_pre_middleware_errors() {
    struct State {}
    #[derive(Clone)]
    struct Ctx(i32);

    let state = State {};

    // If pre middleware fails, then `data` and `req.context` should
    // propagate to the error handler and post middleware. The route
    // handler should not be executed.
    let router: Router<Body, routerify::Error> = Router::builder()
        .data(state)
        .middleware(Middleware::pre(|req| async move {
            req.set_context(Ctx(42));
            Err(routerify::Error::new("Error!"))
        }))
        .err_handler_with_info(|err, req_info| async move {
            let _ctx = req_info.context::<Ctx>().expect("No Ctx");
            let _state = req_info.data::<State>().expect("No state");
            Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(Body::from(err.to_string()))
                .unwrap()
        })
        .middleware(Middleware::post_with_info(|resp, req_info| async move {
            let _ctx = req_info.context::<Ctx>().expect("No Ctx");
            let _state = req_info.data::<State>().expect("No state");
            Ok(resp)
        }))
        .get("/", |_| async { panic!("should not be executed") })
        .build()
        .unwrap();

    let serve = serve(router).await;
    let _ = Client::new()
        .request(
            Request::builder()
                .method("GET")
                .uri(format!("http://{}", serve.addr()))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    serve.shutdown();
}