2016-09-19 23:24:01 +00:00
|
|
|
use std::ops::{Deref, DerefMut};
|
2016-10-12 07:14:42 +00:00
|
|
|
use std::io::Read;
|
2016-09-19 23:24:01 +00:00
|
|
|
|
2016-12-22 06:56:58 +00:00
|
|
|
use rocket::outcome::Outcome;
|
2016-10-25 11:24:07 +00:00
|
|
|
use rocket::request::Request;
|
|
|
|
use rocket::data::{self, Data, FromData};
|
2016-10-25 11:03:50 +00:00
|
|
|
use rocket::response::{self, Responder, content};
|
2016-12-15 08:47:31 +00:00
|
|
|
use rocket::http::Status;
|
2016-09-19 23:24:01 +00:00
|
|
|
|
2017-02-01 01:15:42 +00:00
|
|
|
use serde::{Serialize, Deserialize};
|
2016-09-19 23:24:01 +00:00
|
|
|
|
2017-02-01 01:15:42 +00:00
|
|
|
use serde_json;
|
2016-12-29 03:01:16 +00:00
|
|
|
|
2017-02-01 01:15:42 +00:00
|
|
|
pub use serde_json::Value;
|
|
|
|
pub use serde_json::error::Error as SerdeError;
|
2016-12-29 03:01:16 +00:00
|
|
|
|
2017-02-01 01:15:42 +00:00
|
|
|
/// The JSON type: implements `FromData` and `Responder`, allowing you to easily
|
|
|
|
/// consume and respond with JSON.
|
2016-09-19 23:24:01 +00:00
|
|
|
///
|
2017-02-09 08:16:13 +00:00
|
|
|
/// If you're receiving JSON data, simply add a `data` parameter to your route
|
|
|
|
/// arguments and ensure the type of the parameter is a `JSON<T>`, where `T` is
|
2016-10-12 07:14:42 +00:00
|
|
|
/// some type you'd like to parse from JSON. `T` must implement `Deserialize`
|
|
|
|
/// from [Serde](https://github.com/serde-rs/json). The data is parsed from the
|
|
|
|
/// HTTP request body.
|
2016-09-19 23:24:01 +00:00
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
2016-10-12 07:14:42 +00:00
|
|
|
/// #[post("/users/", format = "application/json", data = "<user>")]
|
2016-09-19 23:24:01 +00:00
|
|
|
/// fn new_user(user: JSON<User>) {
|
|
|
|
/// ...
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-01-31 18:36:37 +00:00
|
|
|
///
|
2016-09-19 23:24:01 +00:00
|
|
|
/// You don't _need_ to use `format = "application/json"`, but it _may_ be what
|
|
|
|
/// you want. Using `format = application/json` means that any request that
|
2017-02-09 08:16:13 +00:00
|
|
|
/// doesn't specify "application/json" as its `Content-Type` header value will
|
|
|
|
/// not be routed to the handler.
|
2016-09-19 23:24:01 +00:00
|
|
|
///
|
|
|
|
/// If you're responding with JSON data, return a `JSON<T>` type, where `T`
|
2016-10-12 07:14:42 +00:00
|
|
|
/// implements `Serialize` from [Serde](https://github.com/serde-rs/json). The
|
|
|
|
/// content type of the response is set to `application/json` automatically.
|
2016-09-19 23:24:01 +00:00
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// #[get("/users/<id>")]
|
|
|
|
/// fn user(id: usize) -> JSON<User> {
|
|
|
|
/// let user_from_id = User::from(id);
|
|
|
|
/// ...
|
|
|
|
/// JSON(user_from_id)
|
|
|
|
/// }
|
|
|
|
/// ```
|
2016-09-22 11:12:07 +00:00
|
|
|
#[derive(Debug)]
|
2017-01-31 18:36:37 +00:00
|
|
|
pub struct JSON<T = Value>(pub T);
|
2016-09-19 23:24:01 +00:00
|
|
|
|
|
|
|
impl<T> JSON<T> {
|
|
|
|
/// Consumes the JSON wrapper and returns the wrapped item.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket_contrib::JSON;
|
|
|
|
/// let string = "Hello".to_string();
|
|
|
|
/// let my_json = JSON(string);
|
2017-01-15 11:00:46 +00:00
|
|
|
/// assert_eq!(my_json.into_inner(), "Hello".to_string());
|
2016-09-19 23:24:01 +00:00
|
|
|
/// ```
|
2017-01-15 11:00:46 +00:00
|
|
|
pub fn into_inner(self) -> T {
|
2016-09-19 23:24:01 +00:00
|
|
|
self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-12 07:14:42 +00:00
|
|
|
/// Maximum size of JSON is 1MB.
|
|
|
|
/// TODO: Determine this size from some configuration parameter.
|
|
|
|
const MAX_SIZE: u64 = 1048576;
|
|
|
|
|
|
|
|
impl<T: Deserialize> FromData for JSON<T> {
|
|
|
|
type Error = SerdeError;
|
|
|
|
|
2016-10-25 11:03:50 +00:00
|
|
|
fn from_data(request: &Request, data: Data) -> data::Outcome<Self, SerdeError> {
|
2017-02-01 11:12:24 +00:00
|
|
|
if !request.content_type().map_or(false, |ct| ct.is_json()) {
|
2016-10-12 07:14:42 +00:00
|
|
|
error_!("Content-Type is not JSON.");
|
2016-10-25 11:03:50 +00:00
|
|
|
return Outcome::Forward(data);
|
2016-10-12 07:14:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let reader = data.open().take(MAX_SIZE);
|
2016-12-22 06:56:58 +00:00
|
|
|
match serde_json::from_reader(reader).map(|val| JSON(val)) {
|
|
|
|
Ok(value) => Outcome::Success(value),
|
|
|
|
Err(e) => {
|
|
|
|
error_!("Couldn't parse JSON body: {:?}", e);
|
|
|
|
Outcome::Failure((Status::BadRequest, e))
|
|
|
|
}
|
|
|
|
}
|
2016-09-19 23:24:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-17 02:06:09 +00:00
|
|
|
/// Serializes the wrapped value into JSON. Returns a response with Content-Type
|
|
|
|
/// JSON and a fixed-size body with the serialized value. If serialization
|
|
|
|
/// fails, an `Err` of `Status::InternalServerError` is returned.
|
2016-12-15 08:47:31 +00:00
|
|
|
impl<T: Serialize> Responder<'static> for JSON<T> {
|
|
|
|
fn respond(self) -> response::Result<'static> {
|
|
|
|
serde_json::to_string(&self.0).map(|string| {
|
|
|
|
content::JSON(string).respond().unwrap()
|
|
|
|
}).map_err(|e| {
|
|
|
|
error_!("JSON failed to serialize: {:?}", e);
|
2016-12-23 10:38:30 +00:00
|
|
|
Status::InternalServerError
|
2016-12-15 08:47:31 +00:00
|
|
|
})
|
2016-09-19 23:24:01 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Deref for JSON<T> {
|
|
|
|
type Target = T;
|
|
|
|
|
|
|
|
fn deref<'a>(&'a self) -> &'a T {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> DerefMut for JSON<T> {
|
|
|
|
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
|
|
|
|
&mut self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-01 01:15:42 +00:00
|
|
|
/// A macro to create ad-hoc JSON serializable values using JSON syntax.
|
|
|
|
///
|
|
|
|
/// # Usage
|
|
|
|
///
|
|
|
|
/// To import the macro, add the `#[macro_use]` attribute to the `extern crate
|
|
|
|
/// rocket_contrib` invocation:
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// #[macro_use] extern crate rocket_contrib;
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// The return type of a macro invocation is
|
2017-01-31 18:36:37 +00:00
|
|
|
/// [Value](/rocket_contrib/enum.Value.html). This is the default value for the
|
|
|
|
/// type parameter of [JSON](/rocket_contrib/struct.JSON.html) and as such, you
|
|
|
|
/// can return `JSON` without specifying the type. A value created with this
|
|
|
|
/// macro can be returned from a handler as follows:
|
2016-09-19 23:24:01 +00:00
|
|
|
///
|
2017-02-01 01:15:42 +00:00
|
|
|
/// ```rust,ignore
|
2017-01-31 18:36:37 +00:00
|
|
|
/// use rocket_contrib::JSON;
|
2017-02-01 01:15:42 +00:00
|
|
|
///
|
|
|
|
/// #[get("/json")]
|
2017-01-31 18:36:37 +00:00
|
|
|
/// fn get_json() -> JSON {
|
2017-02-01 01:15:42 +00:00
|
|
|
/// JSON(json!({
|
|
|
|
/// "key": "value",
|
|
|
|
/// "array": [1, 2, 3, 4]
|
|
|
|
/// }))
|
|
|
|
/// }
|
|
|
|
/// ```
|
2016-12-29 03:01:16 +00:00
|
|
|
///
|
2016-09-19 23:24:01 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
2017-02-01 01:15:42 +00:00
|
|
|
/// Create a simple JSON object with two keys: `"username"` and `"id"`:
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # #![allow(unused_variables)]
|
|
|
|
/// # #[macro_use] extern crate rocket_contrib;
|
|
|
|
/// # fn main() {
|
|
|
|
/// let value = json!({
|
|
|
|
/// "username": "mjordan",
|
|
|
|
/// "id": 23
|
|
|
|
/// });
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Create a more complex object with a nested object and array:
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # #![allow(unused_variables)]
|
|
|
|
/// # #[macro_use] extern crate rocket_contrib;
|
|
|
|
/// # fn main() {
|
|
|
|
/// let value = json!({
|
|
|
|
/// "code": 200,
|
|
|
|
/// "success": true,
|
|
|
|
/// "payload": {
|
|
|
|
/// "features": ["serde", "json"],
|
|
|
|
/// "ids": [12, 121],
|
|
|
|
/// },
|
|
|
|
/// });
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Variables or expressions can be interpolated into the JSON literal. Any type
|
|
|
|
/// interpolated into an array element or object value must implement Serde's
|
|
|
|
/// `Serialize` trait, while any type interpolated into a object key must
|
|
|
|
/// implement `Into<String>`.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # #![allow(unused_variables)]
|
|
|
|
/// # #[macro_use] extern crate rocket_contrib;
|
|
|
|
/// # fn main() {
|
|
|
|
/// let code = 200;
|
|
|
|
/// let features = vec!["serde", "json"];
|
|
|
|
///
|
|
|
|
/// let value = json!({
|
|
|
|
/// "code": code,
|
|
|
|
/// "success": code == 200,
|
|
|
|
/// "payload": {
|
|
|
|
/// features[0]: features[1]
|
|
|
|
/// }
|
|
|
|
/// });
|
|
|
|
/// # }
|
2016-09-19 23:24:01 +00:00
|
|
|
/// ```
|
2017-02-01 01:15:42 +00:00
|
|
|
///
|
|
|
|
/// Trailing commas are allowed inside both arrays and objects.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # #![allow(unused_variables)]
|
2016-09-19 23:24:01 +00:00
|
|
|
/// # #[macro_use] extern crate rocket_contrib;
|
|
|
|
/// # fn main() {
|
2017-02-01 01:15:42 +00:00
|
|
|
/// let value = json!([
|
|
|
|
/// "notice",
|
|
|
|
/// "the",
|
|
|
|
/// "trailing",
|
|
|
|
/// "comma -->",
|
|
|
|
/// ]);
|
2016-09-19 23:24:01 +00:00
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
#[macro_export]
|
2017-02-01 01:15:42 +00:00
|
|
|
macro_rules! json {
|
|
|
|
($($json:tt)+) => {
|
|
|
|
json_internal!($($json)+)
|
2016-09-19 23:24:01 +00:00
|
|
|
};
|
|
|
|
}
|