into_response_derive/
lib.rs1use proc_macro::TokenStream;
2use quote::quote;
3
4#[proc_macro_derive(IntoResponse)]
5pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
6 let ast = syn::parse(input).unwrap();
7 impl_into_response_macro(&ast)
8}
9
10fn impl_into_response_macro(ast: &syn::DeriveInput) -> TokenStream {
11 let name = &ast.ident;
12 let (impl_generics, ty_generics, where_clause) = &ast.generics.split_for_impl();
13 let gen = quote! {
14 impl #impl_generics axum::response::IntoResponse for #name #ty_generics #where_clause{
15 fn into_response(self) -> axum::response::Response {
16 match serde_json::to_vec(&self) {
17 Ok(res) => (
18 [(
19 axum::http::header::CONTENT_TYPE,
20 axum::http::HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()),
21 )],
22 res,
23 )
24 .into_response(),
25 Err(err) => (
26 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
27 [(
28 axum::http::header::CONTENT_TYPE,
29 axum::http::HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),
30 )],
31 err.to_string(),
32 )
33 .into_response(),
34 }
35 }
36 }
37 };
38 gen.into()
39}