Coder Social home page Coder Social logo

body-parser's Introduction

Iron

Build Status Crates.io Status License

Extensible, Concurrency Focused Web Development in Rust.

Response Timer Example

Note: This example works with the current iron code in this repository (master branch). If you are using iron 0.6 from crates.io, please refer to the corresponding example in the branch 0.6-maintenance.

extern crate iron;
extern crate time;

use iron::prelude::*;
use iron::{typemap, AfterMiddleware, BeforeMiddleware};
use time::precise_time_ns;

struct ResponseTime;

impl typemap::Key for ResponseTime { type Value = u64; }

impl BeforeMiddleware for ResponseTime {
    fn before(&self, req: &mut Request) -> IronResult<()> {
        req.extensions.insert::<ResponseTime>(precise_time_ns());
        Ok(())
    }
}

impl AfterMiddleware for ResponseTime {
    fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
        let delta = precise_time_ns() - *req.extensions.get::<ResponseTime>().unwrap();
        println!("Request took: {} ms", (delta as f64) / 1000000.0);
        Ok(res)
    }
}

fn hello_world(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((iron::StatusCode::OK, "Hello World")))
}

fn main() {
    let mut chain = Chain::new(hello_world);
    chain.link_before(ResponseTime);
    chain.link_after(ResponseTime);
    Iron::new(chain).http("localhost:3000");
}

Overview

Iron is a high level web framework built in and for Rust, built on hyper. Iron is designed to take advantage of Rust's greatest features - its excellent type system and its principled approach to ownership in both single threaded and multi threaded contexts.

Iron is highly concurrent and can scale horizontally on more machines behind a load balancer or by running more threads on a more powerful machine. Iron avoids the bottlenecks encountered in highly concurrent code by avoiding shared writes and locking in the core framework.

Iron is 100% safe code:

$ rg unsafe src | wc
       0       0       0

Philosophy

Iron is meant to be as extensible and pluggable as possible; Iron's core is concentrated and avoids unnecessary features by leaving them to middleware, plugins, and modifiers.

Middleware, Plugins, and Modifiers are the main ways to extend Iron with new functionality. Most extensions that would be provided by middleware in other web frameworks are instead addressed by the much simpler Modifier and Plugin systems.

Modifiers allow external code to manipulate Requests and Response in an ergonomic fashion, allowing third-party extensions to get the same treatment as modifiers defined in Iron itself. Plugins allow for lazily-evaluated, automatically cached extensions to Requests and Responses, perfect for parsing, accessing, and otherwise lazily manipulating an http connection.

Middleware are only used when it is necessary to modify the control flow of a Request flow, hijack the entire handling of a Request, check an incoming Request, or to do final post-processing. This covers areas such as routing, mounting, static asset serving, final template rendering, authentication, and logging.

Iron comes with only basic modifiers for setting the status, body, and various headers, and the infrastructure for creating modifiers, plugins, and middleware. No plugins or middleware are bundled with Iron.

Performance

Iron averages 72,000+ requests per second for hello world and is mostly IO-bound, spending over 70% of its time in the kernel send-ing or recv-ing data.*

* Numbers from profiling on my OS X machine, your mileage may vary.

Core Extensions

Iron aims to fill a void in the Rust web stack - a high level framework that is extensible and makes organizing complex server code easy.

Extensions are painless to build. Some important ones are:

Middleware:

Plugins:

Both:

This allows for extremely flexible and powerful setups and allows nearly all of Iron's features to be swappable - you can even change the middleware resolution algorithm by swapping in your own Chain.

* Due to the rapidly evolving state of the Rust ecosystem, not everything builds all the time. Please be patient and file issues for breaking builds, we're doing our best.

Underlying HTTP Implementation

Iron is based on and uses hyper as its HTTP implementation, and lifts several types from it, including its header representation, status, and other core HTTP types. It is usually unnecessary to use hyper directly when using Iron, since Iron provides a facade over hyper's core facilities, but it is sometimes necessary to depend on it as well.

Installation

If you're using Cargo, just add Iron to your Cargo.toml:

[dependencies.iron]
version = "*"

The documentation is hosted online and auto-updated with each successful release. You can also use cargo doc to build a local copy.

Check out the examples directory!

You can run an individual example using cargo run --bin example-name inside the examples directory. Note that for benchmarking you should make sure to use the --release flag, which will cause cargo to compile the entire toolchain with optimizations. Without --release you will get truly sad numbers.

Getting Help

Feel free to ask questions as github issues in this or other related repos.

The best place to get immediate help is on IRC, on any of these channels on the mozilla network:

  • #rust-webdev
  • #iron
  • #rust

One of the maintainers or contributors is usually around and can probably help. We encourage you to stop by and say hi and tell us what you're using Iron for, even if you don't have any questions. It's invaluable to hear feedback from users and always nice to hear if someone is using the framework we've worked on.

Maintainers

Jonathan Reem (reem) is the core maintainer and author of Iron.

Commit Distribution (as of 8e55759):

Jonathan Reem (415)
Zach Pomerantz (123)
Michael Sproul (9)
Patrick Tran (5)
Corey Richardson (4)
Bryce Fisher-Fleig (3)
Barosl Lee (2)
Christoph Burgdorf (2)
da4c30ff (2)
arathunku (1)
Cengiz Can (1)
Darayus (1)
Eduardo Bautista (1)
Mehdi Avdi (1)
Michael Sierks (1)
Nerijus Arlauskas (1)
SuprDewd (1)

License

MIT

body-parser's People

Contributors

aerialx avatar brycefisher avatar chritchens avatar dbrgn avatar emberian avatar fauxfaux avatar fuchsnj avatar jimmycuadra avatar keydunov avatar lukaskalbertodt avatar reem avatar s-panferov avatar skylerlipthay avatar theptrk avatar trotter avatar uniphil avatar untitaker avatar zzmp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

body-parser's Issues

Compilation fails on rust nightly

Compiling fails using rust nightly, the allowed syntax for extern crate seems to be different now:

[...]
Compiling bodyparser v0.0.4 (file:///home/niclas/Hacks/rust/body-parser)
src/lib.rs:9:14: 9:31 error: expected ident, found `"rustc-serialize"`
src/lib.rs:9 extern crate "rustc-serialize" as rustc_serialize;
                          ^~~~~~~~~~~~~~~~~
Could not compile `bodyparser`.

the trait `plugin::Plugin<iron::Request<'_, '_>>` is not implemented for `bodyparser::Raw`

I tried to use the example as a reference to get my own code working, but it fails with:

error[E0277]: the trait bound `bodyparser::Raw: plugin::Plugin<iron::Request<'_, '_>>` is not satisfied
  --> src/main.rs:27:24
   |
27 |         let body = req.get::<bodyparser::Raw>();
   |                        ^^^ the trait `plugin::Plugin<iron::Request<'_, '_>>` is not implemented for `bodyparser::Raw`
   |
   = help: the following implementations were found:
             <bodyparser::Raw as plugin::Plugin<iron::request::Request<'a, 'b>>>

The code in question:

    let (tx, rx) = mpsc::channel();
    let sender = Mutex::new(tx);
    let chain = Chain::new(move |req: &mut Request| -> IronResult<Response> {
        println!("received request");

        let body = req.get::<bodyparser::Raw>();
        match body {
            Ok(Some(body)) => println!("Read body:\n{}", body),
            Ok(None) => println!("No body"),
            Err(err) => println!("Error: {:?}", err),
        }

        let tx = sender.lock().unwrap().clone(); //Or whatever
        tx.send("request");

        return Ok(Response::with((status::Ok, "Hello World")));
    });
    chain.link_before(Read::<bodyparser::MaxBodyLength>::one(MAX_BODY_LENGTH));

    thread::spawn(move || {
        for received in rx {
            println!("{}", received)
        }
    });

    match Iron::new(chain).http(env::var("BIND").unwrap()) {
        Ok(_) => println!("fine"),
        Err(error) => panic!("failed to bind HTTP listener: {:?}", error),
    }

changelog.md

Please consider to add CHANGELOG.md to note breaking changes.

Example for router

Can you please show example for iron/router (not Chain)? When I use Router, I receive "no body".

Iron's Request has no method get

I just copied the code from the readme, and it looks like the example is outdated. This is the error I get.

src/server.rs:38:15: 38:49 error: type `&mut iron::request::Request` does not implement any method in scope named `get`
src/server.rs:38     match req.get::<BodyParser<PleaseCompile>>() {
                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Also, the link to the docs is dead...

Can't compile with rust nightly (built 2015-03-05)

I cloned this repository and tried to cargo build it, but it fails:

    src/lib.rs:30:37: 30:45 error: type `iron::request::Body<'_>` does not implement any method in scope named `by_ref`
    src/lib.rs:30     match LimitReader::new(req.body.by_ref(), limit).read_to_end() {
                                                      ^~~~~~~~
    src/lib.rs:30:45: 30:45 help: methods from traits can only be called if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
    src/lib.rs:30:45: 30:45 help: candidate #1: use `std::io::ReadExt`
    error: aborting due to previous error
    Could not compile `bodyparser`.

Version:

$ rustc -V
rustc 1.0.0-nightly (3b3bb0e68 2015-03-04) (built 2015-03-05)
$ cargo -V
cargo 0.0.1-pre-nightly (dd7c7bd 2015-03-04) (built 2015-03-04)

I tried to fix it by adding use std::io::ReadExt, but it is not the only error...

(I hope I didn't do anything wrong...)

compilation error: can't find crate for 'plugin'

   Compiling bodyparser v0.0.1
     Running `rustc /home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs --crate-name bodyparser --crate-type lib -g -C metadata=6d3d4ec3aa702856 -C extra-filename=-6d3d4ec3aa702856 --out-dir /home/xav/toysarust/target/deps --emit=dep-info,link -L dependency=/home/xav/toysarust/target/deps -L dependency=/home/xav/toysarust/target/deps --extern iron=/home/xav/toysarust/target/deps/libiron-cd5b38656a4d68ab.rlib -Awarnings -L native=/usr/lib/x86_64-linux-gnu -L native=/home/xav/toysarust/target/build/time-24f9c2dbbbc6f19b/out`
/home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs:2:12: 2:31 warning: feature has been added to Rust, directive not necessary
/home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs:2 #![feature(default_type_params)]
                                                                                                   ^~~~~~~~~~~~~~~~~~~
/home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs:2:12: 2:31 warning: feature has been added to Rust, directive not necessary
/home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs:2 #![feature(default_type_params)]
                                                                                                   ^~~~~~~~~~~~~~~~~~~
/home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs:10:1: 10:21 error: can't find crate for `plugin`
/home/xav/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.1/src/lib.rs:10 extern crate plugin;
                                                                                         ^~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `bodyparser`.

Proposal: BodyParser Should Change Contract

Currently body parser works by returning a Result<Option>:

    let struct_body = req.get::<bodyparser::Struct<MyStructure>>();
    match struct_body {
        Ok(Some(struct_body)) => println!("Parsed body:\n{:?}", struct_body),
        Ok(None) => println!("No body"),
        Err(err) => println!("Error: {:?}", err)
    }

I believe that adding an Option to the return type forces the consumer to have an extra level of matching for no gained benefit (in my personal opinion).

If I am trying to parse a body and there is no body present, I would argue that it should be an Err, instead of being Ok(None), after all, I was expected a value to be there that is missing. You can add MissingBody as a potential error code.

I believe this would simplify the API and make it easier to consume.

If the maintainers of this repo agree with my proposal, I can go ahead and submit a PR.

Thanks.

Upgrade to serde 0.9

Serde 0.9 is currently usable on Rust beta (1.15) without any external codegen or feature gates, and 1.15 releases on Feb 2.

Suport for iron 0.6

Iron 0.6 has been released.

Are you already working on migration or I should fork and provide the migration?

does not compile with latest Rust nightly

   Compiling bodyparser v0.0.5
/home/nathan/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.5/src/lib.rs:9:14: 9:31 error: expected ident, found `"rustc-serialize"`
/home/nathan/.cargo/registry/src/github.com-1ecc6299db9ec823/bodyparser-0.0.5/src/lib.rs:9 extern crate "rustc-serialize" as rustc_serialize;
                                                                                                        ^~~~~~~~~~~~~~~~~
rustc --version
rustc 1.0.0-nightly (abf0548b5 2015-04-15) (built 2015-04-16)

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.