Skip to content

Instantly share code, notes, and snippets.

@MadFaill
Last active January 24, 2023 13:41
Show Gist options
  • Save MadFaill/abaf1fd1a6d3e12e5e9a5a9221c1bc2e to your computer and use it in GitHub Desktop.
Save MadFaill/abaf1fd1a6d3e12e5e9a5a9221c1bc2e to your computer and use it in GitHub Desktop.
Custom JSON Responder for Rocket.io
/// # Custom JSON Responder for Rocket.io
///
/// Allow to modify JSON response:
/// - Add custom headers
/// - send cookies
/// - etc...
///
/// # Examples:
///
/// ``` Cargo.toml
/// serde = { version = "1", features = ["derive"] }
/// rocket = { version = "0.5.0-rc.2", features = ["json"] }
/// ```
///
/// ```
/// #[get("/json/with/<string>")]
/// pub fn match_vin<'a>(string: &'a String) -> Json<Vec<String>> {
///
/// let mut strings: Vec<String> = Vec::new();
///
/// items.push(string)
///
/// Json(strings)
/// }
/// ```
use std::io;
use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket::serde::json::{serde_json};
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Json<T>(pub T);
impl<'r, T: Serialize> Responder<'r, 'static> for Json<T> {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
let string = serde_json::to_string(&self.0)
.map_err(|e| {
error_!("JSON failed to serialize: {:?}", e);
Status::InternalServerError
})?;
Response::build()
.raw_header("Content-Type","application/json; charset=utf-8")
.raw_header("Cache-Control", "max-age=120")
.sized_body(string.clone().len(), io::Cursor::new(string))
.ok()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment