Giter Site home page Giter Site logo

routerify-query's Introduction

Github Actions Status crates.io Documentation MIT

routerify-query

A Routerify middleware which parses the request query string and populates in the req object.

Docs

Install

Add this to your Cargo.toml:

[dependencies]
routerify = "3"
routerify-query = "3" 

Example

use hyper::{Body, Request, Response, Server};
use routerify::{Router, RouterService};
// Import the query_parser function and the RequestQueryExt trait.
use routerify_query::{query_parser, RequestQueryExt};
use std::{convert::Infallible, net::SocketAddr};

// A handler for "/" page. Visit: "/?username=Alice&bookname=HarryPotter" to see query values.
async fn home_handler(req: Request<Body>) -> Result<Response<Body>, Infallible> {
    // Access the query values.
    let user_name = req.query("username").unwrap();
    let book_name = req.query("bookname").unwrap();

    Ok(Response::new(Body::from(format!(
        "User: {}, Book: {}",
        user_name, book_name
    ))))
}

// Create a router.
fn router() -> Router<Body, Infallible> {
    Router::builder()
        // Attach the query_parser middleware.
        .middleware(query_parser())
        .get("/", home_handler)
        .build()
        .unwrap()
}

#[tokio::main]
async fn main() {
    let router = router();

    // Create a Service from the router above to handle incoming requests.
    let service = RouterService::new(router).unwrap();

    // The address on which the server will be listening.
    let addr = SocketAddr::from(([127, 0, 0, 1], 3001));

    // Create a server by passing the created service to `.serve` method.
    let server = Server::bind(&addr).serve(service);

    println!("App is running on: {}", addr);
    if let Err(err) = server.await {
        eprintln!("Server error: {}", err);
    }
}

Contributing

Your PRs and suggestions are always welcome.

routerify-query's People

Contributors

rousan avatar seanpianka avatar ta3pks avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

routerify-query's Issues

Release 2.0 version to crates.io

Hello @rousan, I see that this crate has been updated to version 2.0 (to work with routerify v2), but it seems like that version has not been published to crates.io yet. Would it be possible to publish that update, so that we don't have to rely on a git ref to use version 2 of routerify-query ? Thank you.

Add `query_parsed` method

Impl

pub fn query_parsed<T: FromStr + 'static>(req: &HttpRequest, name: &str) -> crate::Result<Option<T>>
where
    <T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
    match req.query(name) {
        Some(q) => q
            .parse::<T>()
            .context(format!("Couldn't parse query value: {} for query `{}`", q, name))
            .map(|q| Some(q)),
        None => Ok(None),
    }
}

Use:

let page = req.query_parsed::<u64>("page")?.unwrap_or_else(0);

Update for 2.0.0-beta-1?

Code:

// Build router using middleware
Router::builder()
  .middleware(routerify_cors::enable_cors_all())
  .middleware(routerify_query::query_parser())
  .build().unwrap();

Error:

error[E0308]: mismatched types
  --> src/server/mod.rs:82:25
   |
82 |             .middleware(routerify_cors::enable_cors_all())
   |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Middleware`, found enum `routerify::middleware::Middleware`
   |
   = note: expected enum `Middleware<_, _>`
              found enum `routerify::middleware::Middleware<_, _>`
   = note: perhaps two different versions of crate `routerify` are being used?

error[E0308]: mismatched types
  --> src/server/mod.rs:83:25
   |
83 |             .middleware(routerify_query::query_parser())
   |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Middleware`, found enum `routerify::middleware::Middleware`
   |
   = note: expected enum `Middleware<_, _>`
              found enum `routerify::middleware::Middleware<_, _>`
   = note: perhaps two different versions of crate `routerify` are being used?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.