Skip to main content

actix_web_codegen/
lib.rs

1//! Routing and runtime macros for Actix Web.
2//!
3//! # Actix Web Re-exports
4//! Actix Web re-exports a version of this crate in it's entirety so you usually don't have to
5//! specify a dependency on this crate explicitly. Sometimes, however, updates are made to this
6//! crate before the actix-web dependency is updated. Therefore, code examples here will show
7//! explicit imports. Check the latest [actix-web attributes docs] to see which macros
8//! are re-exported.
9//!
10//! # Runtime Setup
11//! Used for setting up the actix async runtime. See [macro@main] macro docs.
12//!
13//! ```
14//! #[actix_web_codegen::main] // or `#[actix_web::main]` in Actix Web apps
15//! async fn main() {
16//!     async { println!("Hello world"); }.await
17//! }
18//! ```
19//!
20//! # Single Method Handler
21//! There is a macro to set up a handler for each of the most common HTTP methods that also define
22//! additional guards and route-specific middleware.
23//!
24//! See docs for: [GET], [POST], [PATCH], [PUT], [DELETE], [QUERY], [HEAD], [CONNECT], [OPTIONS],
25//! [TRACE]
26//!
27//! ```
28//! # use actix_web::HttpResponse;
29//! # use actix_web_codegen::get;
30//! #[get("/test")]
31//! async fn get_handler() -> HttpResponse {
32//!     HttpResponse::Ok().finish()
33//! }
34//! ```
35//!
36//! # Multiple Method Handlers
37//! Similar to the single method handler macro but takes one or more arguments for the HTTP methods
38//! it should respond to. See [macro@route] macro docs.
39//!
40//! ```
41//! # use actix_web::HttpResponse;
42//! # use actix_web_codegen::route;
43//! #[route("/test", method = "GET", method = "HEAD")]
44//! async fn get_and_head_handler() -> HttpResponse {
45//!     HttpResponse::Ok().finish()
46//! }
47//! ```
48//!
49//! # Multiple Path Handlers
50//! Acts as a wrapper for multiple single method handler macros. It takes no arguments and
51//! delegates those to the macros for the individual methods. See [macro@routes] macro docs.
52//!
53//! ```
54//! # use actix_web::HttpResponse;
55//! # use actix_web_codegen::routes;
56//! #[routes]
57//! #[get("/test")]
58//! #[get("/test2")]
59//! #[delete("/test")]
60//! async fn example() -> HttpResponse {
61//!     HttpResponse::Ok().finish()
62//! }
63//! ```
64//!
65//! [actix-web attributes docs]: https://docs.rs/actix-web/latest/actix_web/#attributes
66//! [CONNECT]: macro@macro@connect
67//! [DELETE]: macro@delete
68//! [GET]: macro@get
69//! [HEAD]: macro@head
70//! [OPTIONS]: macro@options
71//! [PATCH]: macro@patch
72//! [POST]: macro@post
73//! [PUT]: macro@put
74//! [QUERY]: macro@query
75//! [TRACE]: macro@trace
76
77#![recursion_limit = "512"]
78#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
79#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
80#![cfg_attr(docsrs, feature(doc_cfg))]
81
82use proc_macro::TokenStream;
83use quote::quote;
84
85mod route;
86mod scope;
87
88/// Creates resource handler, allowing multiple HTTP method guards.
89///
90/// # Syntax
91/// ```plain
92/// #[route("path", method="HTTP_METHOD"[, attributes])]
93/// ```
94///
95/// # Attributes
96/// - `"path"`: Raw literal string with path for which to register handler.
97/// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the function
98///   name of handler is used.
99/// - `method = "HTTP_METHOD"`: Registers HTTP method to provide guard for. Upper-case string,
100///   "GET", "POST" for example.
101/// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`.
102/// - `guard_obj = expression`: Registers a guard object that implements `actix_web::guard::Guard`.
103/// - `wrap = "Middleware"`: Registers a resource middleware.
104///
105/// # Notes
106/// Function name can be specified as any expression that is going to be accessible to the generate
107/// code, e.g `my_guard` or `my_module::my_guard`.
108///
109/// # Examples
110/// ```
111/// # use actix_web::HttpResponse;
112/// # use actix_web_codegen::route;
113/// #[route("/test", method = "GET", method = "HEAD", method = "CUSTOM")]
114/// async fn example() -> HttpResponse {
115///     HttpResponse::Ok().finish()
116/// }
117/// ```
118#[proc_macro_attribute]
119pub fn route(args: TokenStream, input: TokenStream) -> TokenStream {
120    route::with_method(None, args, input)
121}
122
123/// Creates resource handler, allowing multiple HTTP methods and paths.
124///
125/// # Syntax
126/// ```plain
127/// #[routes]
128/// #[<method>("path", ...)]
129/// #[<method>("path", ...)]
130/// ...
131/// ```
132///
133/// # Attributes
134/// The `routes` macro itself has no parameters, but allows specifying the attribute macros for
135/// the multiple paths and/or methods, e.g. [`GET`](macro@get) and [`POST`](macro@post).
136///
137/// These helper attributes take the same parameters as the [single method handlers](crate#single-method-handler).
138///
139/// # Examples
140/// ```
141/// # use actix_web::HttpResponse;
142/// # use actix_web_codegen::routes;
143/// #[routes]
144/// #[get("/test")]
145/// #[get("/test2")]
146/// #[delete("/test")]
147/// async fn example() -> HttpResponse {
148///     HttpResponse::Ok().finish()
149/// }
150/// ```
151#[proc_macro_attribute]
152pub fn routes(_: TokenStream, input: TokenStream) -> TokenStream {
153    route::with_methods(input)
154}
155
156macro_rules! method_macro {
157    ($variant:ident, $method:ident) => {
158        #[doc = concat!("Creates route handler with `actix_web::guard::", stringify!($variant), "`.")]
159        ///
160        /// # Syntax
161        /// ```plain
162        #[doc = concat!("#[", stringify!($method), r#"("path"[, attributes])]"#)]
163        /// ```
164        ///
165        /// # Attributes
166        /// - `"path"`: Raw literal string with path for which to register handler.
167        /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the
168        ///   function name of handler is used.
169        /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`.
170        /// - `guard_obj = expression`: Registers a guard object that implements `actix_web::guard::Guard`.
171        /// - `wrap = "Middleware"`: Registers a resource middleware.
172        ///
173        /// # Notes
174        /// Function name can be specified as any expression that is going to be accessible to the
175        /// generate code, e.g `my_guard` or `my_module::my_guard`.
176        ///
177        /// # Examples
178        /// ```
179        /// # use actix_web::HttpResponse;
180        #[doc = concat!("# use actix_web_codegen::", stringify!($method), ";")]
181        #[doc = concat!("#[", stringify!($method), r#"("/")]"#)]
182        /// async fn example() -> HttpResponse {
183        ///     HttpResponse::Ok().finish()
184        /// }
185        /// ```
186        #[proc_macro_attribute]
187        pub fn $method(args: TokenStream, input: TokenStream) -> TokenStream {
188            route::with_method(Some(route::MethodType::$variant), args, input)
189        }
190    };
191}
192
193method_macro!(Connect, connect);
194method_macro!(Delete, delete);
195method_macro!(Get, get);
196method_macro!(Head, head);
197method_macro!(Options, options);
198method_macro!(Patch, patch);
199method_macro!(Post, post);
200method_macro!(Put, put);
201method_macro!(Query, query);
202method_macro!(Trace, trace);
203
204/// Prepends a path prefix to all handlers using routing macros inside the attached module.
205///
206/// # Syntax
207///
208/// ```
209/// # use actix_web_codegen::scope;
210/// #[scope("/prefix")]
211/// mod api {
212///     // ...
213/// }
214/// ```
215///
216/// # Arguments
217///
218/// - `"/prefix"` - Raw literal string to be prefixed onto contained handlers' paths.
219///
220/// # Example
221///
222/// ```
223/// # use actix_web_codegen::{scope, get};
224/// # use actix_web::Responder;
225/// #[scope("/api")]
226/// mod api {
227///     # use super::*;
228///     #[get("/hello")]
229///     pub async fn hello() -> impl Responder {
230///         // this has path /api/hello
231///         "Hello, world!"
232///     }
233/// }
234/// # fn main() {}
235/// ```
236#[proc_macro_attribute]
237pub fn scope(args: TokenStream, input: TokenStream) -> TokenStream {
238    scope::with_scope(args, input)
239}
240
241/// Marks async main function as the Actix Web system entry-point.
242///
243/// Note that Actix Web also works under `#[tokio::main]` since version 4.0. However, this macro is
244/// still necessary for actor support (since actors use a `System`). Read more in the
245/// [`actix_web::rt`](https://docs.rs/actix-web/4/actix_web/rt) module docs.
246///
247/// # Examples
248/// ```
249/// #[actix_web::main]
250/// async fn main() {
251///     async { println!("Hello world"); }.await
252/// }
253/// ```
254#[proc_macro_attribute]
255pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
256    let mut output: TokenStream = (quote! {
257        #[::actix_web::rt::main(system = "::actix_web::rt::System")]
258    })
259    .into();
260
261    output.extend(item);
262    output
263}
264
265/// Marks async test functions to use the Actix Web system entry-point.
266///
267/// # Examples
268/// ```
269/// #[tokio::test(flavor = "local")]
270/// async fn test() {
271///     assert_eq!(async { "Hello world" }.await, "Hello world");
272/// }
273/// ```
274#[proc_macro_attribute]
275pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
276    let mut output: TokenStream = (quote! {
277        #[::actix_web::rt::test(system = "::actix_web::rt::System")]
278    })
279    .into();
280
281    output.extend(item);
282    output
283}
284
285/// Converts the error to a token stream and appends it to the original input.
286///
287/// Returning the original input in addition to the error is good for IDEs which can gracefully
288/// recover and show more precise errors within the macro body.
289///
290/// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info.
291fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream {
292    let compile_err = TokenStream::from(err.to_compile_error());
293    item.extend(compile_err);
294    item
295}