Generic route handler with #[get]
macro?
#2334
Unanswered
JakubKoralewski
asked this question in
Q&A
Replies: 1 comment 2 replies
-
I wrote something like this: #[macro_export]
macro_rules! count {
() => (0usize);
( $x:tt $($xs:tt)* ) => (1usize + $crate::count!($($xs)*));
}
#[macro_export]
macro_rules! generalize_actix_handler {
(method:$method:ident, fn: $fn_name:ident, struct_name: $struct_name:ident, path: $uri_path:literal, generics: <$($gen_param:ident: $gen_type:path),*>) => {
#[allow(non_camel_case_types, missing_docs)]
pub struct $struct_name<$($gen_param:$gen_type),*>([$(PhantomData<fn() -> $gen_param>),*; $crate::count!($($gen_param),*)]);
impl<$($gen_param:$gen_type),*> $struct_name<$($gen_param),*> {
pub fn new() -> Self {
Self([$(PhantomData::<fn() -> $gen_param>),*; $crate::count!($($gen_param),*)])
}
}
impl<$($gen_param:$gen_type),*> actix_web::dev::HttpServiceFactory for $struct_name<$($gen_param),*> {
fn register(self, __config: &mut actix_web::dev::AppService) {
let res =
actix_web::Resource::new($uri_path)
.name(stringify!($fn_name))
.guard(actix_web::guard::$method())
.to($fn_name::<$($gen_param),*>);
actix_web::dev::HttpServiceFactory::register(
res,
__config,
);
}
}
}
} Seems to work. Would be happy to know of other ways to do this. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am writing handlers with the
#[get]
macro and wanted to make the function generic, I've got some compiler error, so I started writing something like this:I'm wondering if there's a less boilerplate-y way to write this, or maybe a macro? Or maybe the
#[get]
family of macros could be somehow modified to accept generic parameters?Beta Was this translation helpful? Give feedback.
All reactions