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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use rustc_serialize::Decodable;
use rustc_serialize::json;
use std::string::FromUtf8Error;
use Request;
#[derive(Debug)]
pub enum JsonError {
WrongContentType,
NotUtf8(FromUtf8Error),
ParseError(json::DecoderError),
}
impl From<FromUtf8Error> for JsonError {
fn from(err: FromUtf8Error) -> JsonError {
JsonError::NotUtf8(err)
}
}
impl From<json::DecoderError> for JsonError {
fn from(err: json::DecoderError) -> JsonError {
JsonError::ParseError(err)
}
}
pub fn get_json_input<O>(request: &Request) -> Result<O, JsonError> where O: Decodable {
if let Some(header) = request.header("Content-Type"){
if !header.starts_with("application/json") {
return Err(JsonError::WrongContentType);
}
} else {
return Err(JsonError::WrongContentType);
}
let content = try!(String::from_utf8(request.data()));
let data = try!(json::decode(&content));
Ok(data)
}