2

I'm building a web application with Rust and Nickel.rs. I have a route which submits a form with a POST request.

I would like to be able to use the request data (the data returned from the form), but I'm not sure how to go about it.

// This works and prints 'email=bar&password=foo'
// but how do I get the values separately?
router.post("/login", middleware! { |request, response|
    let mut body = String::new();
    request.origin.read_to_string(&mut body).unwrap();
    format!("{}", body)
});
tshepang
  • 12,111
  • 21
  • 91
  • 136
user2840647
  • 1,236
  • 1
  • 13
  • 32

2 Answers2

0

I found a solution which works for now, although I don't know if it is the "right" solution.

extern crate url;
use url::*;

use std::collections::HashMap;

router.post("/login", middleware! { |request, response|
    let mut body = String.new();
    request.origin.read_to_string(&mut body).unwrap();

    let mut data = HashMap::new();
    for (key, value) in form_urlencoded::parse(body.as_bytes()) {
        data.insert(key, value);
    }

     println!("{:?}", data) # {'password': 'bar', 'email': 'far'}
});
tshepang
  • 12,111
  • 21
  • 91
  • 136
user2840647
  • 1,236
  • 1
  • 13
  • 32
0

I would do it this way:

router.post("/login", middleware! { |request, response|
    let form_body = try_with!(response, request.form_body());
    let user = form_body.get("username").unwrap_or_default();
    let pass = form_body.get("password").unwrap_or_default();
    ...
}

I wish I knew what response is doing in that try_with! though.

tshepang
  • 12,111
  • 21
  • 91
  • 136