1

I'm trying to make a small application that'll run as a webserver that accepts GET and POST requests. I've got it up and running and it accepts both requests, but I don't know how to extract the data from a POST request. Here's the code to get the server up and running:

extern crate futures;
extern crate hyper;

use hyper::service::service_fn_ok;
use hyper::{Body, Method, Response, Request, StatusCode};
// This is here because we use map_error.
use futures::{Future};

fn post_fn(req : Request<Body>) -> Response<Body> {
    println!("In post!");
    Response::new(Body::from("You posted something!"))
}

fn start_server() {
    let router =  || {
        service_fn_ok( |req| match (req.method(), req.uri().path()) {
            (&Method::GET, "/ping") => {
                println!("In ping");
                Response::new(Body::from("You pinged me!"))
            }
            (&Method::POST, "/") => {
                post_fn(req)
            }
            (_, _) => {
                let mut res = Response::new(Body::from("not found"));
                *res.status_mut() = StatusCode::NOT_FOUND;
                res
            }
        })
    };

    // Setup and run the server
    let addr = "127.0.0.1:3000".parse::<std::net::SocketAddr>().unwrap();

    let server = hyper::Server::bind(&addr).serve(router);

    hyper::rt::run(server.map_err(|e| {
        eprintln!("server error: {}", e);
    }));
}

fn main() {
    start_server();
}

Basically what I want to know is what post_fn needs to be so it can print out "hello" with curl -X POST --data hello 'localhost:3000'. Ultimately the data will be a JSON string that I deserialize, but I can't figure out how to get my hands on the data first.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Have you tried fetching the body through either `req.body()`, `req.into_body()`, or `req.into_parts()`? This seems to be well documented in [`hyper:Request`](https://docs.rs/hyper/0.12.11/hyper/struct.Request.html). – E_net4 Oct 02 '18 at 13:10
  • Yes, I've done `println!("{:?}", req.body());` and all it shows is the word "Body". It won't print without the debug, and it doesn't seem to contain "hello". I've looked at hyper::request many times, if you can point me to something specific I may have overlooked I'd appreciate it – Brian Albert Monroe Oct 02 '18 at 13:21
  • The proposed duplicate seems to cover your use case: `let entire_body = body.concat2();` will produce a `Future` with the whole data. – E_net4 Oct 02 '18 at 13:25

0 Answers0