pub struct Scope<T = ScopeEndpoint, B = BoxBody> { /* private fields */ }
Expand description
Resources scope.
Scope is a set of resources with common root path.
Scopes collect multiple paths under a common path prefix.
Scope path can contain variable path segments as resources.
Scope prefix is always complete path segment, i.e /app
would
be converted to a /app/
and it would not match /app
path.
You can get variable path segments from HttpRequest::match_info()
.
Path
extractor also is able to extract scope level variable segments.
use actix_web::{web, App, HttpResponse};
fn main() {
let app = App::new().service(
web::scope("/{project_id}/")
.service(web::resource("/path1").to(|| async { "OK" }))
.service(web::resource("/path2").route(web::get().to(|| HttpResponse::Ok())))
.service(web::resource("/path3").route(web::head().to(HttpResponse::MethodNotAllowed)))
);
}
In the above example three routes get registered:
- /{project_id}/path1 - responds to all http method
- /{project_id}/path2 -
GET
requests - /{project_id}/path3 -
HEAD
requests
Implementations
sourceimpl<T, B> Scope<T, B> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>,
B: 'static,
impl<T, B> Scope<T, B> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>,
B: 'static,
sourcepub fn guard<G: Guard + 'static>(self, guard: G) -> Self
pub fn guard<G: Guard + 'static>(self, guard: G) -> Self
Add match guard to a scope.
use actix_web::{web, guard, App, HttpRequest, HttpResponse};
async fn index(data: web::Path<(String, String)>) -> &'static str {
"Welcome!"
}
fn main() {
let app = App::new().service(
web::scope("/app")
.guard(guard::Header("content-type", "text/plain"))
.route("/test1", web::get().to(index))
.route("/test2", web::post().to(|r: HttpRequest| {
HttpResponse::MethodNotAllowed()
}))
);
}
sourcepub fn app_data<U: 'static>(self, data: U) -> Self
pub fn app_data<U: 'static>(self, data: U) -> Self
Add scope data.
Data of different types from parent contexts will still be accessible. Any Data<T>
types
set here can be extracted in handlers using the Data<T>
extractor.
Examples
use std::cell::Cell;
use actix_web::{web, App, HttpRequest, HttpResponse, Responder};
struct MyData {
count: std::cell::Cell<usize>,
}
async fn handler(req: HttpRequest, counter: web::Data<MyData>) -> impl Responder {
// note this cannot use the Data<T> extractor because it was not added with it
let incr = *req.app_data::<usize>().unwrap();
assert_eq!(incr, 3);
// update counter using other value from app data
counter.count.set(counter.count.get() + incr);
HttpResponse::Ok().body(counter.count.get().to_string())
}
let app = App::new().service(
web::scope("/app")
.app_data(3usize)
.app_data(web::Data::new(MyData { count: Default::default() }))
.route("/", web::get().to(handler))
);
sourcepub fn data<U: 'static>(self, data: U) -> Self
👎 Deprecated since 4.0.0: Use .app_data(Data::new(val))
instead.
pub fn data<U: 'static>(self, data: U) -> Self
Use .app_data(Data::new(val))
instead.
Add scope data after wrapping in Data<T>
.
Deprecated in favor of app_data
.
sourcepub fn configure<F>(self, cfg_fn: F) -> Self where
F: FnOnce(&mut ServiceConfig),
pub fn configure<F>(self, cfg_fn: F) -> Self where
F: FnOnce(&mut ServiceConfig),
Run external configuration as part of the scope building process.
This function is useful for moving parts of configuration to a different module or library. For example, some of the resource’s configuration could be moved to different module.
use actix_web::{web, middleware, App, HttpResponse};
// this function could be located in different module
fn config(cfg: &mut web::ServiceConfig) {
cfg.service(web::resource("/test")
.route(web::get().to(|| HttpResponse::Ok()))
.route(web::head().to(|| HttpResponse::MethodNotAllowed()))
);
}
fn main() {
let app = App::new()
.wrap(middleware::Logger::default())
.service(
web::scope("/api")
.configure(config)
)
.route("/index.html", web::get().to(|| HttpResponse::Ok()));
}
sourcepub fn service<F>(self, factory: F) -> Self where
F: HttpServiceFactory + 'static,
pub fn service<F>(self, factory: F) -> Self where
F: HttpServiceFactory + 'static,
Register HTTP service.
This is similar to App's
service registration.
Actix Web provides several services implementations:
- Resource is an entry in resource table which corresponds to requested URL.
- Scope is a set of resources with common root path.
- “StaticFiles” is a service for static files support
use actix_web::{web, App, HttpRequest};
struct AppState;
async fn index(req: HttpRequest) -> &'static str {
"Welcome!"
}
fn main() {
let app = App::new().service(
web::scope("/app").service(
web::scope("/v1")
.service(web::resource("/test1").to(index)))
);
}
sourcepub fn route(self, path: &str, route: Route) -> Self
pub fn route(self, path: &str, route: Route) -> Self
Configure route for a specific path.
This is a simplified version of the Scope::service()
method.
This method can be called multiple times, in that case
multiple resources with one route would be registered for same resource path.
use actix_web::{web, App, HttpResponse};
async fn index(data: web::Path<(String, String)>) -> &'static str {
"Welcome!"
}
fn main() {
let app = App::new().service(
web::scope("/app")
.route("/test1", web::get().to(index))
.route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()))
);
}
sourcepub fn default_service<F, U>(self, f: F) -> Self where
F: IntoServiceFactory<U, ServiceRequest>,
U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static,
U::InitError: Debug,
pub fn default_service<F, U>(self, f: F) -> Self where
F: IntoServiceFactory<U, ServiceRequest>,
U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static,
U::InitError: Debug,
Default service to be used if no matching route could be found.
If default resource is not registered, app’s default resource is being used.
sourcepub fn wrap<M, B1>(
self,
mw: M
) -> Scope<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
M: Transform<T::Service, ServiceRequest, Response = ServiceResponse<B1>, Error = Error, InitError = ()>,
pub fn wrap<M, B1>(
self,
mw: M
) -> Scope<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
M: Transform<T::Service, ServiceRequest, Response = ServiceResponse<B1>, Error = Error, InitError = ()>,
Registers middleware, in the form of a middleware component (type), that runs during inbound processing in the request life-cycle (request -> response), modifying request as necessary, across all requests managed by the Scope.
Use middleware when you need to read or modify every request in some way.
sourcepub fn wrap_fn<F, R, B1>(
self,
mw: F
) -> Scope<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
F: Fn(ServiceRequest, &T::Service) -> R + Clone,
R: Future<Output = Result<ServiceResponse<B1>, Error>>,
pub fn wrap_fn<F, R, B1>(
self,
mw: F
) -> Scope<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B1>, Error = Error, InitError = ()>, B1> where
F: Fn(ServiceRequest, &T::Service) -> R + Clone,
R: Future<Output = Result<ServiceResponse<B1>, Error>>,
Registers middleware, in the form of a closure, that runs during inbound processing in the request life-cycle (request -> response), modifying request as necessary, across all requests managed by the Scope.
Examples
use actix_service::Service;
use actix_web::{web, App};
use actix_web::http::header::{CONTENT_TYPE, HeaderValue};
async fn index() -> &'static str {
"Welcome!"
}
fn main() {
let app = App::new().service(
web::scope("/app")
.wrap_fn(|req, srv| {
let fut = srv.call(req);
async {
let mut res = fut.await?;
res.headers_mut().insert(
CONTENT_TYPE, HeaderValue::from_static("text/plain"),
);
Ok(res)
}
})
.route("/index.html", web::get().to(index)));
}
Trait Implementations
sourceimpl<T> HttpServiceFactory for Scope<T> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()> + 'static,
impl<T> HttpServiceFactory for Scope<T> where
T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = ()> + 'static,
fn register(self, config: &mut AppService)
Auto Trait Implementations
impl<T = ScopeEndpoint, B = BoxBody> !RefUnwindSafe for Scope<T, B>
impl<T = ScopeEndpoint, B = BoxBody> !Send for Scope<T, B>
impl<T = ScopeEndpoint, B = BoxBody> !Sync for Scope<T, B>
impl<T, B> Unpin for Scope<T, B> where
B: Unpin,
T: Unpin,
impl<T = ScopeEndpoint, B = BoxBody> !UnwindSafe for Scope<T, B>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more