|
| 1 | +[](https://github.com/routerify/routerify-query/actions) |
| 2 | +[](https://crates.io/crates/routerify-query) |
| 3 | +[](https://docs.rs/routerify-query) |
| 4 | +[](./LICENSE) |
| 5 | + |
1 | 6 | # routerify-query |
2 | | -A pre middleware which parses the request query |
| 7 | + |
| 8 | +A [`Routerify`](https://github.com/routerify/routerify) middleware which parses the request query string and populates in the `req` object. |
| 9 | + |
| 10 | +[Docs](https://docs.rs/routerify-query) |
| 11 | + |
| 12 | +## Usage |
| 13 | + |
| 14 | +First add this to your `Cargo.toml`: |
| 15 | + |
| 16 | +```toml |
| 17 | +[dependencies] |
| 18 | +routerify = "1.0" |
| 19 | +routerify-query = "1.0.0" |
| 20 | +``` |
| 21 | + |
| 22 | +An example: |
| 23 | +```rust |
| 24 | +use hyper::{Body, Request, Response, Server}; |
| 25 | +use routerify::{Router, RouterService}; |
| 26 | +// Import the query_parser function and the RequestQueryExt trait. |
| 27 | +use routerify_query::{query_parser, RequestQueryExt}; |
| 28 | +use std::{convert::Infallible, net::SocketAddr}; |
| 29 | + |
| 30 | +// A handler for "/" page. Visit: "/?username=Alice&bookname=HarryPotter" to see query values. |
| 31 | +async fn home_handler(req: Request<Body>) -> Result<Response<Body>, Infallible> { |
| 32 | + // Access the query values. |
| 33 | + let user_name = req.query("username").unwrap(); |
| 34 | + let book_name = req.query("bookname").unwrap(); |
| 35 | + |
| 36 | + Ok(Response::new(Body::from(format!( |
| 37 | + "User: {}, Book: {}", |
| 38 | + user_name, book_name |
| 39 | + )))) |
| 40 | +} |
| 41 | + |
| 42 | +// Create a router. |
| 43 | +fn router() -> Router<Body, Infallible> { |
| 44 | + Router::builder() |
| 45 | + // Attach the query_parser middleware. |
| 46 | + .middleware(query_parser()) |
| 47 | + .get("/", home_handler) |
| 48 | + .build() |
| 49 | + .unwrap() |
| 50 | +} |
| 51 | + |
| 52 | +#[tokio::main] |
| 53 | +async fn main() { |
| 54 | + let router = router(); |
| 55 | + |
| 56 | + // Create a Service from the router above to handle incoming requests. |
| 57 | + let service = RouterService::new(router); |
| 58 | + |
| 59 | + // The address on which the server will be listening. |
| 60 | + let addr = SocketAddr::from(([127, 0, 0, 1], 3001)); |
| 61 | + |
| 62 | + // Create a server by passing the created service to `.serve` method. |
| 63 | + let server = Server::bind(&addr).serve(service); |
| 64 | + |
| 65 | + println!("App is running on: {}", addr); |
| 66 | + if let Err(err) = server.await { |
| 67 | + eprintln!("Server error: {}", err); |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +## Contributing |
| 73 | + |
| 74 | +Your PRs and suggestions are always welcome. |
0 commit comments