Actix Web Framework

repository·main·Indexed 12 days ago

https://github.com/actix/actix-web

A powerful, pragmatic, and high-performance asynchronous web framework for Rust. It supports HTTP/1.x and HTTP/2, WebSockets, and integrates with the awc HTTP client. The ecosystem includes actix-files for static file serving, actix-multipart for handling multipart/form-data, and actix-test for integration testing via TestServer.

Tokens
73.7K
Snippets
242
Records
324
Agent score
98%

What's inside Actix Web

  1. What are the features of Actix Web?

    main

    Actix Web is a high-performance web framework with the following core capabilities:

    • Protocol Support: HTTP/1.x and HTTP/2, including streaming and pipelining.
    • Routing: Powerful request routing with optional macros.
    • Async Runtime: Full compatibility with Tokio.
    • WebSockets: Built-in client/server support.
    • Content Handling: Transparent compression/decompression (br, gzip, deflate, zstd) and multipart streams.
    • Security: SSL support via OpenSSL or Rustls.
    • Middleware: Support for Logger, Session, CORS, and more.
    • Static Assets: Built-in support for serving static files.
    • Client Integration: Integrates with the awc HTTP client.
  2. Use actix-http-test for Actix application testing

    main
    actix-http-test provides various helper utilities designed to assist developers in testing Actix Web applications. It is intended to be used as a testing dependency to simplify the process of simulating HTTP requests and verifying application behavior.
  3. Perform integration testing with `TestServer`

    main

    The actix-test crate provides integration testing tools for Actix Web applications. The primary tool is TestServer, which spawns a real HTTP server on an unused port and uses a real HTTP client to interact with it.

    Using TestServer is preferred for integration tests because it exercises the full HTTP stack (including encoding and decoding), making it more representative of real-world usage compared to actix_web::test::init_service, which bypasses the HTTP layer.

    use actix_web::{get, web, test, App, HttpResponse, Error, Responder};
    
    #[get("/")]
    async fn my_handler() -> Result<impl Responder, Error> {
        Ok(HttpResponse::Ok())
    }
    
    #[actix_rt::test]
    async fn test_example() {
        // Start a real HTTP server on an unused port
        let srv = actix_test::start(||
            App::new().service(my_handler)
        );
    
        // Use the server's client to send a request
        let req = srv.get("/");
        let res = req.send().await.unwrap();
    
        assert!(res.status().is_success());
    }
  4. What is middleware in Actix Web?

    main

    Middleware is a mechanism used to add behavior to the request/response processing lifecycle. It can be used to:

    • Pre-process incoming requests: e.g., path normalization, authentication.
    • Post-process outgoing responses: e.g., logging, compression.
    • Modify application state: via ServiceRequest.
    • Access external services: such as sessions or caching.

    Execution Order: Middleware is registered for each App, Scope, or Resource. It is executed in the reverse order of registration. This means the last middleware you register is the first one to receive the request.

  5. Use new Response Body types

    main

    The ResponseBody and Body types have been removed in favor of more expressive components in the body module. Use the following mappings for common requirements:

    Old TypeNew Equivalent
    Body::Nonebody::None::new()
    Body::Empty() or web::Bytes::new()
    Body::Bytesweb::Bytes::from(...)
    Body::Message.boxed() or BoxBody

    BoxBody

    BoxBody is a type-erased body type. It is useful for handlers or middleware where you want to trade a small amount of performance for simpler types. Create it using .boxed() on a MessageBody type.

    EitherBody

    EitherBody is a type that implements MessageBody and is useful for middleware that can return different body types (e.g., the inner service's body or a custom error body).

  6. When to use (or avoid) middleware

    main

    Use middleware for cross-cutting concerns:

    • Global request/response modifications.
    • Authentication and authorization.
    • Logging and monitoring.
    • Compression or caching.

    Avoid middleware when:

    • The logic is specific to a single route (use a handler or a service instead).
    • The operation is better handled by a dedicated service.
    • The performance overhead of running the logic on every request is too high.
    • The functionality can be implemented more simply elsewhere in the application.
  7. Use experimental features in Actix Web

    main

    Actix Web provides experimental features for faster iteration. These features are prefixed with experimental and may undergo breaking changes in any release. Use them in production at your own risk.

    One available experimental feature is:

    • experimental-introspection: Exposes route and method reporting helpers for local diagnostics and tooling.
  8. Compare Multipart vs MultipartForm extractors

    main

    The actix-multipart crate provides two ways to handle multipart data:

    1. Multipart (Low-level): A lower-level extractor that supports all multipart/* media types, including multipart/form-data, multipart/related, and multipart/mixed. It allows you to read multipart fields sequentially in the order they are sent by the client.

    2. MultipartForm (High-level): A higher-level extractor and derive macro that is optimized for multipart/form-data specifically. It provides a more ergonomic way to map fields to structured data but does not support other multipart media types.

  9. Understand Server Worker Thread defaults

    main
    In Actix Web v4, the default number of worker threads in actix-server has changed. It now defaults to the number of physical CPU cores available, whereas previously it used the number of logical cores. If you experience performance regressions, monitor your CPU core utilization.