mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-04-20 06:54:46 +00:00
add derive for raw request body
This commit is contained in:
parent
f737ac4332
commit
5282dbbe6c
6 changed files with 243 additions and 18 deletions
69
gotham_restful_derive/src/from_body.rs
Normal file
69
gotham_restful_derive/src/from_body.rs
Normal file
|
@ -0,0 +1,69 @@
|
|||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{
|
||||
Fields,
|
||||
ItemStruct,
|
||||
parse_macro_input
|
||||
};
|
||||
|
||||
pub fn expand_from_body(tokens : TokenStream) -> TokenStream
|
||||
{
|
||||
let krate = super::krate();
|
||||
let input = parse_macro_input!(tokens as ItemStruct);
|
||||
let ident = input.ident;
|
||||
let generics = input.generics;
|
||||
|
||||
let (were, body) = match input.fields {
|
||||
Fields::Named(named) => {
|
||||
let fields = named.named;
|
||||
if fields.len() == 0 // basically unit
|
||||
{
|
||||
(quote!(), quote!(Self{}))
|
||||
}
|
||||
else if fields.len() == 1
|
||||
{
|
||||
let field = fields.first().unwrap();
|
||||
let field_ident = field.ident.as_ref().unwrap();
|
||||
let field_ty = &field.ty;
|
||||
(quote!(where #field_ty : for<'a> From<&'a [u8]>), quote!(Self { #field_ident: body.into() }))
|
||||
}
|
||||
else
|
||||
{
|
||||
panic!("FromBody can only be derived for structs with at most one field")
|
||||
}
|
||||
},
|
||||
Fields::Unnamed(unnamed) => {
|
||||
let fields = unnamed.unnamed;
|
||||
if fields.len() == 0 // basically unit
|
||||
{
|
||||
(quote!(), quote!(Self{}))
|
||||
}
|
||||
else if fields.len() == 1
|
||||
{
|
||||
let field = fields.first().unwrap();
|
||||
let field_ty = &field.ty;
|
||||
(quote!(where #field_ty : for<'a> From<&'a [u8]>), quote!(Self(body.into())))
|
||||
}
|
||||
else
|
||||
{
|
||||
panic!("FromBody can only be derived for structs with at most one field")
|
||||
}
|
||||
},
|
||||
Fields::Unit => (quote!(), quote!(Self{}))
|
||||
};
|
||||
|
||||
let output = quote! {
|
||||
impl #generics #krate::FromBody for #ident #generics
|
||||
#were
|
||||
{
|
||||
type Err = String;
|
||||
|
||||
fn from_body(body : #krate::Chunk, _content_type : #krate::Mime) -> Result<Self, Self::Err>
|
||||
{
|
||||
let body : &[u8] = &body;
|
||||
Ok(#body)
|
||||
}
|
||||
}
|
||||
};
|
||||
output.into()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue