1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#![deny(missing_docs)]

//! A default implementation for the reep::types::OptionParser
//! witch uses the urlencoded QueryParser parsing queries into
//! a QueryMap (a `HashMap<String, Vec<String>>`)


extern crate iron;
extern crate reep;
extern crate urlencoded;

use iron::prelude::*;
use iron::typemap::Key;
use iron::status;
use reep::types::{ParserMiddleware, OptionParser};
use urlencoded::{QueryMap, UrlEncodedQuery, UrlDecodingError};

/// a default implementation, using the urlencoded cargo package to parse options
/// (into a HashMap<String, Vec<String>>)
pub struct DefaultOptionParser;

impl Key for DefaultOptionParser {
    type Value = QueryMap;
}

impl ParserMiddleware for DefaultOptionParser {
    fn parse(&self, req: &mut Request) -> IronResult<Self::Value> {
        match req.compute::<UrlEncodedQuery>() {
            Ok(data) => Ok(data),
            Err(UrlDecodingError::EmptyQuery) => Ok(QueryMap::new()),
            Err(decoding_error) =>  {
                Err(IronError::new(decoding_error, (status::BadRequest)))
            }
        }
    }
}

impl OptionParser for DefaultOptionParser {}