11

Currently I have a main written like the async example for the Reqwest library.

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

We can use the exact example there for this. Now I want to basically add a -l <port> flag to alter the behavior of my application and when triggered in such a fashion, I want it to listen on the port and run a web server. I'm wanting to use Actix Web which is documented like this,

#[actix_web::main]
async fn main() -> std::io::Result<()> {

How can I synthesize two fn main: one decorated with #[actix_web::main] and one decorated with #[tokio::main] to use Actix Web from within an application that already uses Tokio? I can't find any documentation on this? How do we go about using Tokio stuff from an Actix Web server, and how do we port a Tokio application to an Actix Web application?

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • Have a look at https://github.com/actix/examples/blob/master/basics/run-in-thread/src/main.rs – Njuguna Mureithi Mar 01 '21 at 05:52
  • I doubt you can have multiple main since you can only have one main entry – Njuguna Mureithi Mar 01 '21 at 05:53
  • You can't have multiple `main` functions, but since Actix runs on Tokio anyway there might be a way to tell Actix to use an existing Tokio runtime instead of starting its own. – Jmb Mar 01 '21 at 07:52
  • @NjugunaMureithi here is an updated link https://github.com/actix/examples/blob/master/run-in-thread/src/main.rs – neoneye Oct 25 '22 at 23:22

1 Answers1

15

Since Actix-web internally uses Tokio, when you use #[actix_web::main], you will be able to use all the usual Tokio utilities just as if you had used #[tokio::main].

However be aware that you need to match up the versions of Tokio correctly. Actix-web version 3.x.y uses Tokio 0.2.x, so when using that version of Actix, you need to use utilities that work with that version of Tokio. To use the latest version of Tokio, you need to use the 4.0.0-beta.x versions of Actix-web instead.

Feel free to edit this answer once Actix-web 4 is out of beta.

Alice Ryhl
  • 3,574
  • 1
  • 18
  • 37
  • 1
    Thank you! Just leaving some breadcrumbs here... I was using Actix-Web `3` with reqwest `0.11` and was getting the error `thread 'actix-rt:worker:2' panicked at 'there is no reactor running, must be called from the context of a Tokio 1.x runtime'` – Tillerino Jan 05 '22 at 08:01
  • 1
    Actix-web is now out of beta. Here are some usefull links: [issue tracking this on Github](https://github.com/actix/actix-web/issues/1283) ; [migration guide](https://github.com/actix/actix-web/blob/master/actix-web/MIGRATION-4.0.md) – TDiblik Apr 20 '22 at 14:10