Expand description
Route guards.
Guards are used during routing to help select a matching service or handler using some aspect of the request; though guards should not be used for path matching since it is a built-in function of the Actix Web router.
Guards can be used on Scopes, Resources, Routes, and other custom services.
Fundamentally, a guard is a predicate function that receives a reference to a request context
object and returns a boolean; true if the request should be handled by the guarded service
or handler. This interface is defined by the Guard trait.
Commonly-used guards are provided in this module as well as a way of creating a guard from a
closure (fn_guard). The Not, Any, and All guards are noteworthy, as they can be
used to compose other guards in a more flexible and semantic way than calling .guard(...) on
services multiple times (which might have different combining behavior than you want).
There are shortcuts for routes with method guards in the web module:
web::get(), web::post(), etc. The routes created by
the following calls are equivalent:
web::get()(recommended form)web::route().guard(guard::Get())
Guards can not modify anything about the request. However, it is possible to store extra
attributes in the request-local data container obtained with GuardContext::req_data_mut.
Guards can prevent resource definitions from overlapping which, when only considering paths,
would result in inaccessible routes. See the Host guard for an example of virtual hosting.
Examples
In the following code, the /guarded resource has one defined route whose handler will only be
called if the request method is POST and there is a request header with name and value equal
to x-guarded and secret, respectively.
use actix_web::{web, http::Method, guard, HttpResponse};
web::resource("/guarded").route(
web::route()
.guard(guard::Any(guard::Get()).or(guard::Post()))
.guard(guard::Header("x-guarded", "secret"))
.to(|| HttpResponse::Ok())
);Structs
check outcomes is true.check outcomes is true.Guard implementation.Traits
Functions
CONNECT request method.DELETE request method.GET request method.HEAD request method.OPTIONS request method.PATCH request method.POST request method.PUT request method.TRACE request method.