Skip to main content

controller

Attribute Macro controller 

Source
#[controller]
Expand description

Defines a Sword controller. Route handlers are declared directly inside the impl block using method attributes such as #[get], #[post], #[put], #[patch], #[delete], #[head], #[options], #[trace], and #[connect].

§Parameters

  • kind: Controller kind. Use Controller::Web, Controller::SocketIo, Controller::Grpc, or Controller::EventHandler.
  • path: Required when kind = Controller::Web.
  • namespace: Required when kind = Controller::SocketIo.
  • service: Required when kind = Controller::Grpc.
  • source: Required when kind = Controller::EventHandler. Use EventSource::Memory.

§Usage

#[controller(kind = Controller::Web, path = "/base_path")]
struct MyController {}

impl MyController {
    #[get("/sub_path")]
    async fn my_handler(&self) -> WebResult {
       Ok(JsonResponse::Ok().message("Hello from MyController"))
    }
}
#[controller(kind = Controller::SocketIo, namespace = "/chat")]
struct ChatController;

impl ChatController {
    #[on("connection")]
    async fn on_connect(&self, _ctx: SocketContext) {}
}