actix-web/actix-web-codegen
Matt Gathu 31348a2339 Provide attribute macro for multiple HTTP methods
What
--
Define a new `route` attribute macro that supports defining multiple
HTTP methods to routed to (handled by) a single handler.

The attribute macro syntax looks like this
```rust
use actix_web::route;

async fn multi_methods() -> &'static str {
    "Hello world!\r\n"
}
```

How
--
This implementation extends the [`GuardType`][1] enum in actix-web-codegen to have a
new `GuardType::Multi` variant that denotes when multiple method guards
are used.

A new `methods` attribute in the `route` attribute macro provides a
comma-separated list of HTTP methods to provide guard for.

The code parses the methods list, matches them to the respective
`GuardType` and uses the `AnyGuard` struct to combine them together.

A constructor method for [`AnyGuard`][2] is added to support this.

The generated code looks like this:
```rust
pub struct multi_methods;
impl actix_web::dev::HttpServiceFactory for multi_methods {
    fn register(self, __config: &mut actix_web::dev::AppService) {
    ¦   async fn multi_methods() -> &'static str {
    ¦   ¦   "Hello world!\r\n"
    ¦   }
    ¦   let __resource = actix_web::Resource::new("/multi")
    ¦   ¦   .name("multi_methods")
    ¦   ¦   .guard(actix_web:💂:AnyGuard::new(<[_]>::into_vec(box [
    ¦   ¦   ¦   Box::new(actix_web:💂:Get()),
    ¦   ¦   ¦   Box::new(actix_web:💂:Post()),
    ¦   ¦   ])))
    ¦   ¦   .to(multi_methods);
    ¦   actix_web::dev::HttpServiceFactory::register(__resource, __config)
    }
}
```

**NOTE: This is my first attempt that implementing this feature.
Feedback and mentorship is highly welcome to improve it :-)**

Why
--
This fixes https://github.com/actix/actix-web/issues/1360

[1]: https://github.com/actix/actix-web/blob/master/actix-web-codegen/src/route.rs#L21
[2]: https://github.com/actix/actix-web/blob/master/src/guard.rs#L104s
2020-09-15 20:26:08 +02:00
..
src Provide attribute macro for multiple HTTP methods 2020-09-15 20:26:08 +02:00
tests add trybuild tests to routing codegen (#1677) 2020-09-13 16:31:08 +01:00
CHANGES.md add trybuild tests to routing codegen (#1677) 2020-09-13 16:31:08 +01:00
Cargo.toml add trybuild tests to routing codegen (#1677) 2020-09-13 16:31:08 +01:00
LICENSE-APACHE prepare actix-web-codegen release 2019-06-01 17:21:22 +06:00
LICENSE-MIT prepare actix-web-codegen release 2019-06-01 17:21:22 +06:00
README.md add trybuild tests to routing codegen (#1677) 2020-09-13 16:31:08 +01:00

README.md

actix-web-codegen

Helper and convenience macros for Actix Web

crates.io Documentation Version Build Status codecov Join the chat at https://gitter.im/actix/actix

Documentation & Resources

Compile Testing

Uses the trybuild crate. All compile fail tests should include a stderr file generated by trybuild. See the workflow section of the trybuild docs for info on how to do this.