-
Notifications
You must be signed in to change notification settings - Fork 28
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
Add some helper functions for common usage #53
Open
viraptor
wants to merge
2
commits into
iron:master
Choose a base branch
from
viraptor:helpers
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
//! This example uses helper functions instead of direct interface. | ||
//! | ||
//! It cannot differentiate between a single and repeated parameter and will | ||
//! fail with 400 as soon as either the body or the required parameter are not | ||
//! provided. | ||
|
||
extern crate iron; | ||
extern crate urlencoded; | ||
|
||
use iron::prelude::*; | ||
use iron::status; | ||
use urlencoded::helpers::{require_body_params, require_parameter}; | ||
|
||
fn log_post_data(req: &mut Request) -> IronResult<Response> { | ||
let hashmap = try!(require_body_params(req)); | ||
let name = try!(require_parameter(&hashmap, "name")); | ||
|
||
Ok(Response::with((status::Ok, format!("Hello {}", name)))) | ||
} | ||
|
||
// Test with `curl -i -X POST "http://localhost:3000/" --data "name=world"` | ||
fn main() { | ||
Iron::new(log_post_data).http("127.0.0.1:3000").unwrap(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
//! Helpers for the urlencoded module | ||
//! | ||
//! Provides one liners for the common usage of urlencoded | ||
|
||
use ::iron::prelude::*; | ||
use ::iron::status; | ||
use ::std::fmt::{Display,Formatter}; | ||
use ::std::fmt::Error as FmtError; | ||
use ::std::error::Error as StdError; | ||
use super::{UrlEncodedBody,UrlEncodedQuery,QueryMap}; | ||
|
||
/// Error returned when the requested parameter is missing | ||
#[derive(Debug, PartialEq)] | ||
pub struct MissingParamError { | ||
name: String | ||
} | ||
|
||
impl StdError for MissingParamError { | ||
fn description(&self) -> &str { | ||
"Missing parameter" | ||
} | ||
} | ||
|
||
impl Display for MissingParamError { | ||
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { | ||
write!(f, "Missing parameter {}", self.name) | ||
} | ||
} | ||
|
||
/// Returns the parameters hashmap constructed from the request body | ||
/// | ||
/// # Examples | ||
/// ``` | ||
/// fn request_handler(req: &mut Request) => IronResult<Response> { | ||
/// let params = try!(require_body_params(req)); | ||
/// ``` | ||
pub fn require_body_params(req: &mut Request) -> IronResult<QueryMap> { | ||
req.get::<UrlEncodedBody>() | ||
.map_err(|err| IronError::new(err, status::BadRequest)) | ||
} | ||
|
||
/// Returns the parameters hashmap constructed from the request query | ||
/// | ||
/// # Examples | ||
/// ``` | ||
/// fn request_handler(req: &mut Request) => IronResult<Response> { | ||
/// let params = try!(require_query_params(req)); | ||
/// | ||
/// ``` | ||
pub fn require_query_params(req: &mut Request) -> IronResult<QueryMap> { | ||
req.get::<UrlEncodedQuery>() | ||
.map_err(|err| IronError::new(err, status::BadRequest)) | ||
} | ||
|
||
/// Returns the first parameter for a given parameter name, or a `MissingParamError` | ||
/// | ||
/// # Examples | ||
/// ``` | ||
/// fn request_handler(req: &mut Request) => IronResult<Response> { | ||
/// let params = try!(require_body_params(req)); | ||
/// let search = try!(require_parameter(¶ms, "search")); | ||
/// | ||
/// ``` | ||
pub fn require_parameter<'a, T: Into<String>>(hashmap: &'a QueryMap, name: T) -> IronResult<&'a String> { | ||
let name_val = name.into(); | ||
hashmap.get(&name_val) | ||
.and_then(|vals| vals.first()) | ||
.ok_or(IronError::new(MissingParamError { name: name_val }, status::BadRequest)) | ||
} | ||
|
||
#[test] | ||
fn test_require_single() { | ||
let mut hash = QueryMap::new(); | ||
hash.insert("var".to_string(), vec!["value".to_string()]); | ||
let val = require_parameter(&hash, "var").unwrap(); | ||
assert_eq!(val, "value"); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we might be able to avoid these extra functions if we impl
Into<IronError>
for our own error types?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Generally speaking I think it's wrong to do so - you want to specify an intelligent and semantic response when there is an error, not just toss 400 at everything.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The point of those helpers is IMO that I don't care about that.