Using Actix from a Tokio App: mixing actix_web::main and tokio::main?

Viewed 4659

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?

1 Answers

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.

Related