1
0
mirror of https://github.com/actix/actix-website synced 2025-06-27 15:39:02 +02:00

First pass at Extractors.

This commit is contained in:
Cameron Dershem
2019-06-16 23:17:17 -04:00
parent 5bd4218b94
commit f922e8fb96
12 changed files with 238 additions and 183 deletions

View File

@ -15,4 +15,5 @@ members = [
exclude = [
"request-handlers",
"async-handlers",
"extractors",
]

View File

@ -0,0 +1,11 @@
[package]
name = "extractors"
version = "0.1.0"
authors = ["Cameron Dershem <cameron@pinkhatbeard.com>"]
edition = "2018"
[dependencies]
actix-web = "1.0"
serde = "1.0"
futures = "0.1"
serde_json = "1.0"

View File

@ -0,0 +1,18 @@
use actix_web::{web, HttpRequest, HttpResponse};
struct MyHandler {}
struct MyInfo {}
// <custom-handler>
impl<S> Handler<S> for MyHandler {
type Result = HttpResponse;
/// Handle request
fn handle(&self, req: &HttpRequest<S>) -> Self::Result {
let params = web::Path::<(String, String)>::extract(req);
let info = web::Json::<MyInfo>::extract(req);
HttpResponse::Ok().into()
}
}
// </custom-handler>

View File

@ -0,0 +1,20 @@
// <form>
use actix_web::{web, App, Result};
use serde::Deserialize;
#[derive(Deserialize)]
struct FormData {
username: String,
}
/// extract form data using serde
/// this handler gets called only if the content type is *x-www-form-urlencoded*
/// and the content of the request could be deserialized to a `FormData` struct
fn index(form: web::Form<FormData>) -> Result<String> {
Ok(format!("Welcome {}!", form.username))
}
// </form>
pub fn main() {
App::new().route("", web::post().to(index));
}

View File

@ -0,0 +1,18 @@
// <json-one>
use actix_web::{web, App, Result};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
username: String,
}
/// deserialize `Info` from request's body
fn index(info: web::Json<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.username))
}
pub fn main() {
App::new().route("/", web::get().to(index));
}
// </json-one>

View File

@ -0,0 +1,34 @@
// <json-two>
use actix_web::{error, web, App, FromRequest, HttpResponse, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
username: String,
}
/// deserialize `Info` from request's body, max payload size is 4kb
fn index(info: web::Json<Info>) -> impl Responder {
format!("Welcome {}!", info.username)
}
pub fn main() {
App::new().service(
web::resource("/")
.data(
// change json extractor configuration
web::Json::<Info>::configure(|cfg| {
cfg.limit(4096).error_handler(|err, _req| {
// <- create custom error response
error::InternalError::from_response(
err,
HttpResponse::Conflict().finish(),
)
.into()
})
}),
)
.route(web::post().to(index)),
);
}
// </json-two>

View File

@ -0,0 +1,48 @@
use actix_web::{web, App, FromRequest, HttpRequest, HttpServer, Responder};
use futures::future::Future;
use serde::Deserialize;
// mod custom_handler;
mod form;
mod json_one;
mod json_two;
mod multiple;
mod path_one;
mod path_two;
mod query;
#[derive(Deserialize, Debug)]
struct MyInfo {
username: String,
id: u32,
}
// <main>
// Option 1: passed as a parameter to a handler function
fn index(path: web::Path<(String, String)>, json: web::Json<MyInfo>) -> impl Responder {
format!("{} {} {} {}", path.0, path.1, json.id, json.username)
}
// Option 2: accessed by calling extract() on the Extractor
fn extract(req: HttpRequest) -> impl Responder {
let params = web::Path::<(String, String)>::extract(&req).unwrap();
let info = web::Json::<MyInfo>::extract(&req)
.wait()
.expect("Err with reading json.");
format!("{} {} {} {}", params.0, params.1, info.username, info.id)
}
// </main>
fn main() {
HttpServer::new(|| {
App::new()
.route("/{name}/{id}", web::post().to(index))
.route("/{name}/{id}/extract", web::post().to(extract))
})
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}

View File

@ -0,0 +1,20 @@
// <multi>
use actix_web::{web, App};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
username: String,
}
fn index((_path, query): (web::Path<(u32, String)>, web::Query<Info>)) -> String {
format!("Welcome {}!", query.username)
}
pub fn main() {
App::new().route(
"/users/{userid}/{friend}", // <- define path parameters
web::get().to(index),
);
}
// </multi>

View File

@ -0,0 +1,17 @@
// <path-one>
use actix_web::{web, App, Result};
/// extract path info from "/users/{userid}/{friend}" url
/// {userid} - - deserializes to a u32
/// {friend} - deserializes to a String
fn index(info: web::Path<(u32, String)>) -> Result<String> {
Ok(format!("Welcome {}! {}", info.1, info.0))
}
pub fn main() {
App::new().route(
"/users/{userid}/{friend}", // <- define path parameters
web::get().to(index),
);
}
// </path-one>

View File

@ -0,0 +1,22 @@
// <path-two>
use actix_web::{web, App, Result};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
userid: u32,
friend: String,
}
/// extract path info using serde
fn index(info: web::Path<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.friend))
}
pub fn main() {
App::new().route(
"/users/{userid}/{friend}", // <- define path parameters
web::get().to(index),
);
}
// </path-two>

View File

@ -0,0 +1,18 @@
// <query>
use actix_web::{web, App};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
username: String,
}
// this handler get called only if the request's query contains `username` field
fn index(info: web::Query<Info>) -> String {
format!("Welcome {}!", info.username)
}
pub fn main() {
App::new().route("/", web::get().to(index));
}
// </query>