Advanced Features
6 min read
Welcome to the deep end of the pool! πββοΈ Youβve mastered the basics of routing, handlers, and state. Now itβs time to unlock the features that turn a simple web server into a production-grade powerhouse.
We are going to cover three sophisticated topics that separate the "Hello World" apps from the "High Scale" systems:
- Route Guards: How to protect and filter routes logic before they even hit your handler.
- Streaming Responses: How to send data bit-by-bit (essential for large files or real-time feeds).
- WebSockets: Real-time, two-way communication using the modern
actix-wscrate (no actors required!).
1. Using Route Guards for Advanced Request Filtering
π§ What is a Guard?
In Actix Web, a Guard is a gatekeeper. It is a simple function (or trait implementation) that looks at an incoming request and returns true or false.
- True: "Come on in! The router will try to match you to this handler."
- False: "Not for you. I'll keep looking for another route that matches."
π§ The Problem
Imagine you have an Admin API. You only want to allow requests that have a specific header, say x-admin-secure: true.
If you use standard logic, you have to write this check inside every single handler function.
// β Bad Practice: Repetitive logic inside handlers
async fn delete_user(req: HttpRequest) -> impl Responder {
if req.headers().get("x-admin-secure").is_none() {
return HttpResponse::Forbidden().finish();
}
// ... actual logic
}This violates the DRY (Don't Repeat Yourself) principle and clutters your business logic.
π The Solution
Use a Route Guard. The guard runs during routing. If the guard fails, the handler is never even called. Actix will simply return a 404 (Not Found) or continue checking other routes if defined.
π» Implementation
We can use the guard::fn_guard helper to create ad-hoc guards.
use actix_web::{guard, web, App, HttpResponse, HttpServer, Responder};
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hello from the Guarded Route!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(
web::resource("/secret")
// π This route only matches if the custom guard returns true
.guard(guard::fn_guard(|ctx| {
ctx.head().headers.contains_key("x-secret-token")
}))
.route(web::get().to(manual_hello))
)
// You can also use built-in guards
.route(
"/guarded",
web::get()
.guard(guard::Header("content-type", "application/json"))
.to(|| async { HttpResponse::Ok().body("JSON only!") })
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}π§ͺ Try it out:
If youcurl -v http://localhost:8080/secret, you get404 Not Found.
If youcurl -v -H "x-secret-token: 1" http://localhost:8080/secret, you get200 OK.
Industry Note: Guards are often used for API versioning. You can have the same URL /api/v1/resource route to different Rust functions based on a custom header like Accept-Version.
2. Streaming Responses and Chunked Transfer Encoding
π Definition
Streaming allows you to send a response to the client chunk by chunk rather than waiting for the entire response to be ready in memory.
π The Problem
You need to serve a 4GB video file or generate a massive CSV report from a database.
- Without Streaming: You load all 4GB into RAM, then send it. Your server crashes due to Out-Of-Memory (OOM) errors. π₯
- With Streaming: You read 8KB, send 8KB, read 8KB, send 8KB... Memory usage stays tiny.
π The Solution
Actix Web supports Transfer-Encoding: chunked automatically when you return a HttpResponse::Streaming. You just need to provide a Rust Stream.
π» Implementation
Let's simulate a slow data stream (like a slow database query or a file download).
use actix_web::{get, App, Error, HttpResponse, HttpServer};
use actix_web::web::Bytes;
use futures::{stream, Stream};
use std::time::Duration;
use tokio::time::sleep;
// This function returns a Stream that yields "Bytes"
fn generate_data_stream() -> impl Stream<Item = Result<Bytes, Error>> {
stream::unfold(0, |count| async move {
if count >= 5 {
return None; // End of stream
}
// Simulate work (e.g., fetching next DB row)
sleep(Duration::from_millis(500)).await;
let chunk = format!("Chunk number: {}\n", count);
let bytes = Bytes::from(chunk);
// Return the chunk and the new state (count + 1)
Some((Ok(bytes), count + 1))
})
}
#[get("/stream")]
async fn stream_handler() -> HttpResponse {
let my_stream = generate_data_stream();
// π Magic happens here
HttpResponse::Ok()
.content_type("text/plain")
.streaming(my_stream)
}Did you know? π§
When you use .streaming(), Actix Web automatically omits the Content-Length header and sets Transfer-Encoding: chunked. The client (browser/curl) knows to keep reading until it receives a "zero-length chunk" indicating the end.
3. Introduction to WebSockets with actix-ws
π Definition
WebSockets provide a persistent, full-duplex communication channel over a single TCP connection.
π The Problem
HTTP is stateless and unidirectional. The client asks, the server answers, and the connection closes.
If you are building a Chat App or a Crypto Ticker:
- Polling: The client asks "Any new messages?" every 1 second. This floods your server with useless requests.
π The Solution
Upgrade the HTTP connection to a WebSocket. The connection stays open. The server can push data to the client whenever it wants!
β οΈ Important Distinction:
Historically, Actix used actix-web-actors for WebSockets. This required understanding the complex Actor model.
Today, we use actix-ws, a modern, lightweight crate that uses standard Rust async/await loops. It is simpler and often faster for standard use cases.
π¦ Setup
Ensure you have the dependency in Cargo.toml:
[dependencies]
actix-web = "4"
actix-ws = "0.3"
tokio = { version = "1", features = ["full"] }
futures-util = "0.3"π» Implementation (Echo Server)
This handler upgrades the connection and spawns a loop to handle incoming messages.
use actix_web::{rt, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_ws::Message;
use futures_util::StreamExt;
async fn chat_ws(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
// 1. Handshake & Upgrade
let (response, mut session, mut msg_stream) = actix_ws::handle(&req, stream)?;
// 2. Spawn a lightweight async task to handle this specific connection
rt::spawn(async move {
// Loop over incoming messages
while let Some(Ok(msg)) = msg_stream.next().await {
match msg {
Message::Text(text) => {
println!("Client said: {}", text);
// Echo it back
let _ = session.text(format!("Echo: {}", text)).await;
}
Message::Binary(bin) => {
let _ = session.binary(bin).await;
}
Message::Ping(bytes) => {
// Standard WebSocket heartbeat
let _ = session.pong(&bytes).await;
}
Message::Close(reason) => {
println!("Client closed connection");
let _ = session.close(reason).await;
break;
}
_ => {}
}
}
});
// 3. Return the handshake response immediately
Ok(response)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/ws", web::get().to(chat_ws))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}π§βπ¬ How to Test
You cannot test WebSockets easily with curl.
- Open your browser console (F12).
- Paste this JavaScript:javascript
let ws = new WebSocket("ws://localhost:8080/ws"); ws.onmessage = (event) => console.log("Server:", event.data); ws.onopen = () => ws.send("Hello Actix!"); - Watch the console print
Server: Echo: Hello Actix!.
Summary
- Guards protect your routes using logic outside your handlers (
.guard()). - Streaming allows you to send huge data chunks without exploding memory usage (
HttpResponse::Streaming). - WebSockets (
actix-ws) enable real-time, two-way communication using simple async loops.
π References & Further Reading
Challenge
You are building a real-time logging service using Actix Web. Your task is to implement a secure WebSocket endpoint at /ws/logs.
This endpoint must be protected by a custom route guard. The guard must ensure that the incoming request contains an HTTP header X-API-Key with the exact value "SECRET_KEY". Requests without this header or with an incorrect value should not be routed to the handler.
The WebSocket handler itself should perform the following actions:
- When it receives a
Textmessage, it should send aTextmessage back to the client with the original content prefixed with"LOG: ". - It must correctly respond to
Pingmessages with aPongmessage to keep the connection alive. - Upon receiving a
Closemessage from the client, it should gracefully terminate the session. - It should ignore all other message types (e.g.,
Binary).
Complete the api_key_guard function and the log_service_socket handler to fulfill these requirements.
Expected result
The solution should be a single block of Rust code containing two completed functions: api_key_guard and log_service_socket.
The api_key_guard function should:
- Access the request headers via the
GuardContext. - Use the
.get()method on the header map to find theX-API-Keyheader. - Safely unwrap the header value and compare it to the string
"SECRET_KEY". - Return
trueif the header exists and its value matches, otherwise returnfalse.
The log_service_socket function should:
- Use
actix_ws::handleto manage the WebSocket lifecycle. - Inside the async closure passed to
handle, implement awhile let Some(Ok(msg)) = stream.next().awaitloop to process messages. - Use a
matchstatement on themsgvariable to handle differentactix_ws::Messagevariants. - For
Message::Text(text), it should callsession.text(format!("LOG: {}", text)).await. - For
Message::Ping(bytes), it should callsession.pong(&bytes).await. - For
Message::Close(_)or any other variant that signals termination, it shouldbreakthe loop. - The function signature and the call to
actix_ws::handleshould remain as provided in the initial code.