-
-
Save kroltan/f7317173f08a11230930ef1abb8c1e54 to your computer and use it in GitHub Desktop.
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
[package] | |
name = "lifetime_issue" | |
version = "0.1.0" | |
authors = ["kroltan"] | |
[dependencies] | |
rocket = "0.3.0" | |
rocket_codegen = "0.3.0" | |
serde = "1.0.11" | |
serde_derive = "1.0.11" | |
serde_json = "1.0.2" |
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
#![feature(plugin)] | |
#![plugin(rocket_codegen)] | |
#[macro_use] extern crate serde_derive; | |
extern crate serde; | |
extern crate serde_json; | |
extern crate rocket; | |
use std::str::Utf8Error; | |
use serde::Deserialize; | |
use serde_json::Error as JsonError; | |
use rocket::request::{Form, FromForm, FormItems}; | |
#[derive(Debug, Serialize, Deserialize)] | |
pub struct Message<T> { | |
pub header: (), | |
body: T | |
} | |
#[derive(Debug)] | |
pub enum MessageFormError { | |
MissingJsonKey, | |
InvalidUrl(Utf8Error), | |
InvalidJson(JsonError) | |
} | |
impl<'f, T> FromForm<'f> for Message<T> | |
where T: Deserialize<'f> | |
{ | |
type Error = MessageFormError; | |
fn from_form(items: &mut FormItems<'f>, strict: bool) -> Result<Self, Self::Error> { | |
// Get JSON field | |
let encoded = items.find(|&(k, _)| k.as_str() == "json") | |
.map(|(_, v)| v); | |
if let None = encoded { | |
return Err(MessageFormError::MissingJsonKey); | |
} | |
// Decode URL-string | |
let decoded = encoded.unwrap().url_decode(); | |
if let Err(e) = decoded { | |
return Err(MessageFormError::InvalidUrl(e)); | |
} | |
// Parse JSON | |
let json = decoded.unwrap(); | |
serde_json::from_str::<Self>(&json) | |
.map_err(|e| MessageFormError::InvalidJson(e)) | |
} | |
} | |
#[post("/", data = "<data>")] | |
pub fn do_something(data: Form<Message<String>>) -> String { | |
(&data.get().body).to_string() | |
} | |
fn main() { | |
rocket::ignite() | |
.mount("/", routes![do_something]) | |
.launch(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment