mirror of
https://github.com/actix/actix-website
synced 2025-01-22 16:15:56 +01:00
update extractors
This commit is contained in:
parent
4046b0b697
commit
b8e2a2310c
@ -9,18 +9,11 @@ weight: 170
|
|||||||
Actix-web provides a facility for type-safe request information access called *extractors*
|
Actix-web provides a facility for type-safe request information access called *extractors*
|
||||||
(ie, `impl FromRequest`). By default, actix-web provides several extractor implementations.
|
(ie, `impl FromRequest`). By default, actix-web provides several extractor implementations.
|
||||||
|
|
||||||
## Extractors Within Handler Functions
|
An extractor can be accessed as an arguments to a handler function. Actix-web supports
|
||||||
|
up to 10 extractors per handler function. Argument position does not matter.
|
||||||
An extractor can be accessed in a few different ways.
|
|
||||||
|
|
||||||
Option 1 - passed as a parameter to a handler function:
|
|
||||||
|
|
||||||
{{< include-example example="extractors" file="main.rs" section="option-one" >}}
|
{{< include-example example="extractors" file="main.rs" section="option-one" >}}
|
||||||
|
|
||||||
Option 2 - accessed by calling `extract()` on the Extractor
|
|
||||||
|
|
||||||
{{< include-example example="extractors" file="main.rs" section="option-two" >}}
|
|
||||||
|
|
||||||
# Path
|
# Path
|
||||||
|
|
||||||
[*Path*][pathstruct] provides information that can be extracted from the Request's
|
[*Path*][pathstruct] provides information that can be extracted from the Request's
|
||||||
@ -78,15 +71,6 @@ the *serde* crate.
|
|||||||
|
|
||||||
{{< include-example example="extractors" file="form.rs" section="form" >}}
|
{{< include-example example="extractors" file="form.rs" section="form" >}}
|
||||||
|
|
||||||
# Multiple extractors
|
|
||||||
|
|
||||||
Actix-web provides extractor implementations for tuples (up to 10 elements) whose
|
|
||||||
elements implement `FromRequest`.
|
|
||||||
|
|
||||||
For example we can use a path extractor and a query extractor at the same time.
|
|
||||||
|
|
||||||
{{< include-example example="extractors" file="multiple.rs" section="multi" >}}
|
|
||||||
|
|
||||||
# Other
|
# Other
|
||||||
|
|
||||||
Actix-web also provides several other extractors:
|
Actix-web also provides several other extractors:
|
||||||
@ -102,7 +86,7 @@ Actix-web also provides several other extractors:
|
|||||||
* *Payload* - You can access a request's payload.
|
* *Payload* - You can access a request's payload.
|
||||||
[*Example*][payloadexample]
|
[*Example*][payloadexample]
|
||||||
|
|
||||||
# Async Data Access
|
# Application state extractor
|
||||||
|
|
||||||
Application state is accessible from the handler with the `web::Data` extractor;
|
Application state is accessible from the handler with the `web::Data` extractor;
|
||||||
however, state is accessible as a read-only reference. If you need mutable access to state,
|
however, state is accessible as a read-only reference. If you need mutable access to state,
|
||||||
@ -125,7 +109,7 @@ number of requests processed per thread. A proper implementation would use `Arc`
|
|||||||
> Be careful with synchronization primitives like `Mutex` or `RwLock`. The `actix-web` framework
|
> Be careful with synchronization primitives like `Mutex` or `RwLock`. The `actix-web` framework
|
||||||
> handles requests asynchronously. By blocking thread execution, all concurrent
|
> handles requests asynchronously. By blocking thread execution, all concurrent
|
||||||
> request handling processes would block. If you need to share or update some state
|
> request handling processes would block. If you need to share or update some state
|
||||||
> from multiple threads, consider using the [actix][actix] actor system.
|
> from multiple threads, consider using the tokio synchronization primitives.
|
||||||
|
|
||||||
[pathstruct]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html
|
[pathstruct]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html
|
||||||
[querystruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Query.html
|
[querystruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Query.html
|
||||||
|
@ -66,7 +66,7 @@ negotiation.
|
|||||||
# JSON Response
|
# JSON Response
|
||||||
|
|
||||||
The `Json` type allows to respond with well-formed JSON data: simply return a value of
|
The `Json` type allows to respond with well-formed JSON data: simply return a value of
|
||||||
type Json<T> where `T` is the type of a structure to serialize into *JSON*.
|
type `Json<T>` where `T` is the type of a structure to serialize into *JSON*.
|
||||||
The type `T` must implement the `Serialize` trait from *serde*.
|
The type `T` must implement the `Serialize` trait from *serde*.
|
||||||
|
|
||||||
{{< include-example example="responses" file="json_resp.rs" section="json-resp" >}}
|
{{< include-example example="responses" file="json_resp.rs" section="json-resp" >}}
|
||||||
|
@ -19,19 +19,17 @@ async fn main() -> std::io::Result<()> {
|
|||||||
HttpServer::new(|| {
|
HttpServer::new(|| {
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/")
|
web::resource("/")
|
||||||
.data(
|
// change json extractor configuration
|
||||||
// change json extractor configuration
|
.app_data(web::Json::<Info>::configure(|cfg| {
|
||||||
web::Json::<Info>::configure(|cfg| {
|
cfg.limit(4096).error_handler(|err, _req| {
|
||||||
cfg.limit(4096).error_handler(|err, _req| {
|
// create custom error response
|
||||||
// <- create custom error response
|
error::InternalError::from_response(
|
||||||
error::InternalError::from_response(
|
err,
|
||||||
err,
|
HttpResponse::Conflict().finish(),
|
||||||
HttpResponse::Conflict().finish(),
|
)
|
||||||
)
|
.into()
|
||||||
.into()
|
})
|
||||||
})
|
}))
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(web::post().to(index)),
|
.route(web::post().to(index)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
@ -7,7 +7,9 @@ struct Info {
|
|||||||
username: String,
|
username: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn index((path, query): (web::Path<(u32, String)>, web::Query<Info>)) -> String {
|
async fn index(
|
||||||
|
(path, query): (web::Path<(u32, String)>, web::Query<Info>),
|
||||||
|
) -> String {
|
||||||
format!(
|
format!(
|
||||||
"Welcome {}, friend {}, userid {}!",
|
"Welcome {}, friend {}, userid {}!",
|
||||||
query.username, path.1, path.0
|
query.username, path.1, path.0
|
||||||
|
@ -2,7 +2,8 @@ use actix_web::{web, HttpRequest, Result};
|
|||||||
|
|
||||||
// <path-three>
|
// <path-three>
|
||||||
async fn index(req: HttpRequest) -> Result<String> {
|
async fn index(req: HttpRequest) -> Result<String> {
|
||||||
let name: String = req.match_info().get("friend").unwrap().parse().unwrap();
|
let name: String =
|
||||||
|
req.match_info().get("friend").unwrap().parse().unwrap();
|
||||||
let userid: i32 = req.match_info().query("userid").parse().unwrap();
|
let userid: i32 = req.match_info().query("userid").parse().unwrap();
|
||||||
|
|
||||||
Ok(format!("Welcome {}, userid {}!", name, userid))
|
Ok(format!("Welcome {}, userid {}!", name, userid))
|
||||||
|
@ -28,7 +28,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.data(data.clone())
|
.app_data(data.clone())
|
||||||
.route("/", web::to(show_count))
|
.route("/", web::to(show_count))
|
||||||
.route("/add", web::to(add_one))
|
.route("/add", web::to(add_one))
|
||||||
})
|
})
|
||||||
|
@ -29,7 +29,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.data(data.clone())
|
.app_data(data.clone())
|
||||||
.route("/", web::to(show_count))
|
.route("/", web::to(show_count))
|
||||||
.route("/add", web::to(add_one))
|
.route("/add", web::to(add_one))
|
||||||
})
|
})
|
||||||
|
@ -1,23 +1,22 @@
|
|||||||
// // <chunked>
|
// <chunked>
|
||||||
// use actix_web::{web, HttpRequest, HttpResponse};
|
use actix_web::{web, HttpRequest, HttpResponse};
|
||||||
// use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
// use futures::stream::once;
|
use futures::future::ok;
|
||||||
|
use futures::stream::once;
|
||||||
|
|
||||||
// fn index(req: HttpRequest) -> HttpResponse {
|
async fn index(req: HttpRequest) -> HttpResponse {
|
||||||
// HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
// .chunked()
|
.chunked()
|
||||||
// .body(Body::Streaming(Box::new(once(Ok(Bytes::from_static(
|
.streaming(once(ok::<_, Error>(Bytes::from_static(b"data"))))
|
||||||
// b"data",
|
}
|
||||||
// ))))))
|
// </chunked>
|
||||||
// }
|
|
||||||
// // </chunked>
|
|
||||||
|
|
||||||
// pub fn main() {
|
pub fn main() {
|
||||||
// use actix_web::{web, App, HttpServer};
|
use actix_web::{web, App, HttpServer};
|
||||||
|
|
||||||
// HttpServer::new(|| App::new().route("/", web::get().to(index)))
|
HttpServer::new(|| App::new().route("/", web::get().to(index)))
|
||||||
// .bind("127.0.0.1:8088")
|
.bind("127.0.0.1:8088")
|
||||||
// .unwrap()
|
.unwrap()
|
||||||
// .run()
|
.run()
|
||||||
// .unwrap();
|
.unwrap();
|
||||||
// }
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user