#[get]Expand description
Creates a route handler with a GET method guard.
Re-exported as ntex::web::get.
Syntax: #[get("path"[, guard = "fn_name"]*[, state = Type])]
The macro takes a handler function and replaces it with a unit struct of
the same name. The struct is a web service, you register it with
.service() on an App or a scope. The function itself ends up inside
the generated code, so you can’t call it directly anymore. The struct is
always pub, whatever the visibility of the function.
The function is any handler Route::to() accepts: an async fn with up
to 16 extractors, or a plain fn that returns a future. The function name
is also used as the resource name, so it works with url_for().
§Arguments
"path"- path of the resource, the same syntax as forResource::new(), for example"/users/{id}". Required, must come first.guard = "fn_name"- adds a guard built withntex::web::guard::fn_guard(). The value is the name of a functionfn(&RequestHead) -> boolthat is in scope where the macro is used. It must be a plain name, paths like"guards::is_json"are not supported, import the function instead. Can be given more than once, all guards must pass.state = Type- type of the application state, written as a type path without quotes. The handler can then only be registered on anApp<Type>, and its errors use the error type ofType. It does not give the handler access to the state. Defaults to(), the state ofApp::new().
§Examples
use ntex::http::RequestHead;
use ntex::web::{App, HttpResponse, get, post};
#[get("/")]
async fn index() -> HttpResponse {
HttpResponse::Ok().body("hello")
}
fn is_json(req: &RequestHead) -> bool {
req.headers()
.get("content-type")
.is_some_and(|v| v == "application/json")
}
// only matches POST requests with a json content type
#[post("/items", guard = "is_json")]
async fn create_item(body: String) -> HttpResponse {
HttpResponse::Created().body(body)
}
let app = App::<()>::new().service((index, create_item));With a custom application state:
use ntex::web::{self, App, HttpResponse, get};
#[derive(Clone)]
struct MyState;
impl web::State for MyState {
type Error = web::DefaultError;
}
#[get("/", state = MyState)]
async fn index() -> HttpResponse {
HttpResponse::Ok().build()
}
let app = App::<MyState>::new().service(index);