From f7bf9e21a8108a223ade11358ee3cdc6c850b604 Mon Sep 17 00:00:00 2001 From: dowwie Date: Fri, 25 May 2018 15:51:16 -0400 Subject: [PATCH] added section on accessing Extractors --- content/docs/extractors.md | 56 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/content/docs/extractors.md b/content/docs/extractors.md index 3654e3b..ee56600 100644 --- a/content/docs/extractors.md +++ b/content/docs/extractors.md @@ -9,6 +9,62 @@ weight: 170 Actix provides facility for type-safe request information extraction. By default, actix provides several extractor implementations. +# Accessing Extractors + +How you access an Extractor depends on whether you are using a handler function +or a custom Handler type. + +## Within Handler Functions + +An Extractor can be passed to a handler function as a function parameter +*or* accessed within the function by calling the ExtractorType::<...>::extract(req) +function. +```rust + +// Option 1: passed as a parameter to a handler function +fn index(params: Path<(String, String,)>, info: Json) -> HttpResponse { + ... +} + + +// Option 2: accessed by calling extract() on the Extractor + +fn index(req: HttpRequest) -> HttpResponse { + let params = Path::<(String, String)>::extract(req); + let info = Json::::extract(req); + + ... +} +``` + +## Within Custom Handler Types + +Like a handler function, a custom Handler type can *access* an Extractor by +calling the ExtractorType::<...>::extract(req) function. An Extractor +*cannot* be passed as a parameter to a custom Handler type because a custom +Handler type must follow the ``handle`` function signature specified by the +Handler trait it implements. + +```rust + +struct MyHandler(String); + +impl Handler for MyHandler { + type Result = HttpResponse; + + /// Handle request + fn handle(&mut self, req: HttpRequest) -> Self::Result { + let params = Path::<(String, String)>::extract(req); + let info = Json::::extract(req); + + ... + + HttpResponse::Ok().into() + } +} + +``` + # Path [*Path*](../../actix-web/actix_web/struct.Path.html) provides information that can