Seeking help in `Application guards and virtual hosting`

Hey, i am just exploring the actix web for building web servers in rust. While reading docs i got to know about guards and virtual hosting. But i am not getting it, Can anyone help me to understand the actual use of it and why they are used and when should we use them?

You can think of a guard as a simple function that accepts a request object reference and returns true or false. Formally, a guard is any object that implements the Guard trait. Actix Web provides several guards. You can check the functions section of the API docs.

One of the provided guards is Host. It can be used as a filter based on request header information.

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(
                web::scope("/")
                    .guard(guard::Host("www.rust-lang.org"))
                    .route("", web::to(|| async { HttpResponse::Ok().body("www") })),
            )
            .service(
                web::scope("/")
                    .guard(guard::Host("users.rust-lang.org"))
                    .route("", web::to(|| async { HttpResponse::Ok().body("user") })),
            )
            .route("/", web::to(HttpResponse::Ok))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Above is the content from the docs.

Guards are function or object-oriented conditions that prevent the service from being handled. E.g. guard::Host(...) checks for a specific hostname (like api.example.com) against the request's target host. There is also guard::Any(...) where you can chain .or().

Virtual hosting is about that, using host guards for conditionally applying services.

Tat means guard::Host will only allow the request for specified hostname?

The request may have been done from a x.y.z domain, so yeah, it constrains the service to run only under x.y.z.

Beware of the www domain prefix though.

Sorry, I was slightly wrong.

Actually HTTP requests have a Host header, which means "the domain we're sending the request into". It may not be always present, though.

You can think of the host guards more of as a reflexive feature.

Thanks, i will look into resource you have sent.

1 Like