Access Request Params and Body
necrognosis opened this issue Β· comments
Hey Nickle team! I apologize in advance if this is a waste of time, but I can't seem to find what I'm doing wrong. I'm trying to convert an older project from Node.js to Rust for practice, but am having some trouble accessing the request params or body.
Here is my server code. At this point, the server should just be receiving the access code from github, and I can see the code
param in the callback url from github, I just can't figure out how to access it.
#[macro_use] extern crate nickel;
use nickel::{Nickel, HttpRouter, StaticFilesHandler};
fn main() {
let mut server = Nickel::new();
server.utilize(StaticFilesHandler::new("public"));
server.get("/user/signin/callback", middleware! { |request, response|
let code = request.param("code");
println!("code is {:?}", &code);
format!("code be {:?}", &code)
});
match server.listen("127.0.0.1:8101") {
Ok(_) => println!(">>> π Open http://127.0.0.1:8101/ in your browser."),
Err(err) => println!(">>> Error, could not start server\n{:?}", err)
};
}
Any help would be much appreciated, I know I'm missing something simple somewhere. Thank you in advance for your help.
request.param
is for retrieving parameters from the url path. For example, in the following
server.get("/:user/info", middleware! { |request, response|
let user = request.param("user");
println!("user is {:?}", &user);
format!("user be {:?}", &code)
});
a path of /jolhoeft/info
would set user = "jolhoeft".
To get the request parameters, you want to use QueryString
. For your example above
#[macro_use] extern crate nickel;
use nickel::{Nickel, HttpRouter, QueryString, StaticFilesHandler};
fn main() {
let mut server = Nickel::new();
server.utilize(StaticFilesHandler::new("public"));
server.get("/user/signin/callback", middleware! { |request, response|
let code = request.query().get("code");
println!("code is {:?}", &code);
format!("code be {:?}", &code)
});
match server.listen("127.0.0.1:8101") {
Ok(_) => println!(">>> π Open http://127.0.0.1:8101/ in your browser."),
Err(err) => println!(">>> Error, could not start server\n{:?}", err)
};
}
This give me "code be Some("123")" for the url http://127.0.0.1:8101/user/signin/callback?code=123
.
As a side note, the middleware macro is fragile. It does not handle exiting early in error cases well. Unfortunately, this requires more macro expertise than I have (or have time to acquire) to fix.
Thank you for such a detailed answer. Honestly I feel foolish for not figuring this out haha.
Your answer has helped me a lot, and thank you for your side note as well, I shall keep that in mind.
Thanks again for everything, and have a good one!