Struct actix_web::Scope

source ·
pub struct Scope<T = ScopeEndpoint> { /* private fields */ }
Expand description

A collection of Routes, Resources, or other services that share a common path prefix.

The Scope’s path can contain dynamic segments. The dynamic segments can be extracted from requests using the Path extractor or with HttpRequest::match_info().

Avoid Trailing Slashes

Avoid using trailing slashes in the scope prefix (e.g., web::scope("/scope/")). It will almost certainly not have the expected behavior. See the documentation on resource definitions to understand why this is the case and how to correctly construct scope/prefix definitions.

Examples

use actix_web::{web, App, HttpResponse};

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 methods
  • /{project_id}/path2 - responds to GET requests
  • /{project_id}/path3 - responds to HEAD requests

Implementations§

source§

impl Scope

source

pub fn new(path: &str) -> Scope

Create a new scope

source§

impl<T> Scope<T>where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>,

source

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!"
}

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()
        }))
);
source

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))
);
source

pub fn data<U: 'static>(self, data: U) -> Self

👎Deprecated since 4.0.0: Use .app_data(Data::new(val)) instead.

Add scope data after wrapping in Data<T>.

Deprecated in favor of app_data.

source

pub fn configure<F>(self, cfg_fn: F) -> Selfwhere 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()))
    );
}

let app = App::new()
    .wrap(middleware::Logger::default())
    .service(
        web::scope("/api")
            .configure(config)
    )
    .route("/index.html", web::get().to(|| HttpResponse::Ok()));
source

pub fn service<F>(self, factory: F) -> Selfwhere 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!"
}

let app = App::new().service(
    web::scope("/app").service(
        web::scope("/v1")
            .service(web::resource("/test1").to(index)))
);
source

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!"
}

let app = App::new().service(
    web::scope("/app")
        .route("/test1", web::get().to(index))
        .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()))
);
source

pub fn default_service<F, U>(self, f: F) -> Selfwhere F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, U::InitError: Debug,

Default service to be used if no matching resource could be found.

If a default service is not registered, it will fall back to the default service of the parent App (see App::default_service).

source

pub fn wrap<M, B>( self, mw: M ) -> Scope<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>>where M: Transform<T::Service, ServiceRequest, Response = ServiceResponse<B>, Error = Error, InitError = ()> + 'static, B: MessageBody,

Registers a scope-wide middleware.

mw is a middleware component (type), that can modify the request and response across all sub-resources managed by this Scope.

See App::wrap for more details.

source

pub fn wrap_fn<F, R, B>( self, mw: F ) -> Scope<impl ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()>>where F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static, R: Future<Output = Result<ServiceResponse<B>, Error>>, B: MessageBody,

Registers a scope-wide function middleware.

mw is a closure that runs during inbound and/or outbound processing in the request life-cycle (request -> response), modifying request/response as necessary, across all requests handled by the Scope.

See App::wrap_fn for examples and more details.

Trait Implementations§

source§

impl<T, B> HttpServiceFactory for Scope<T>where T: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = ()> + 'static, B: MessageBody + 'static,

source§

fn register(self, config: &mut AppService)

Auto Trait Implementations§

§

impl<T = ScopeEndpoint> !RefUnwindSafe for Scope<T>

§

impl<T = ScopeEndpoint> !Send for Scope<T>

§

impl<T = ScopeEndpoint> !Sync for Scope<T>

§

impl<T> Unpin for Scope<T>where T: Unpin,

§

impl<T = ScopeEndpoint> !UnwindSafe for Scope<T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

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
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more