Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide getter for the raw body of a request #359

Open
jess-sol opened this issue Jul 12, 2016 · 3 comments
Open

Provide getter for the raw body of a request #359

jess-sol opened this issue Jul 12, 2016 · 3 comments

Comments

@jess-sol
Copy link

It'd be really nice to be able to get the raw body of a request with something like request.raw_body(). This would allow request formats other than JSON and form encoded; it'd also allow the use of parsers other than rustc_serializable for JSON decoding (I need to use Serde, for instance).

@jess-sol
Copy link
Author

jess-sol commented Jul 12, 2016

I've written a plugin to do this. It's probably a bit verbose, but it gets the job done. Posted here for anyone else who may need this functionality:

//! Provides a plugin for Nickel's Request which allows the raw contents
//! of a body to be made available via the req.raw_body() method.

extern crate plugin;
extern crate typemap;

use std::io;
use std::io::Read;
use nickel::Request;
use self::typemap::Key;
use self::plugin::{Plugin, Pluggable};

struct RawBodyPlugin;

pub trait RawBody {
    fn raw_body(&mut self) -> &str;
}

impl Key for RawBodyPlugin { type Value = String; }

impl<'mw, 'conn, D> Plugin<Request<'mw, 'conn, D>> for RawBodyPlugin {
    type Error = io::Error;

    fn eval(req: &mut Request<D>) -> Result<String, io::Error> {
        let mut buffer = String::new();
        try!(req.origin.read_to_string(&mut buffer));
        Ok(buffer)
    }
}

impl<'mw, 'conn, D> RawBody for Request<'mw, 'conn, D> {
    fn raw_body(&mut self) -> &str {
        match self.get_ref::<RawBodyPlugin>().ok() {
            Some(x) => x,
            None => "",
        }
    }
}

To use:

use nickel::Nickel;
mod nickel_rawbody;
use self::nickel_rawbody::*;

fn main() {
    let mut server = Nickel::new();
    let prometheus = Prometheus::new().unwrap();

    server.post("/", middleware! { |request, response| 
        request.raw_body()
    });

    server.listen("0.0.0.0:9999");
}

@jolhoeft
Copy link
Member

jolhoeft commented May 1, 2019

I am thinking of pulling this into body_parser.rs, although is should probably be StrBody, since it returns the body as a unicode string. RawBody should probably return &[u8].

@imclint21
Copy link

Definitely needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants