1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

standardize binary names

This commit is contained in:
Rob Ede
2022-02-18 02:22:58 +00:00
parent cfb181ecf5
commit 6f1c9e2350
29 changed files with 10 additions and 10 deletions

View File

@ -0,0 +1,16 @@
[package]
name = "json-validation"
version = "1.0.0"
edition = "2021"
[dependencies]
actix-web = { version = "4.0.0-beta.21", features = ["openssl"] }
awc = "3.0.0-beta.19"
env_logger = "0.9"
futures = "0.3.1"
log = "0.4"
serde = { version = "1.0.43", features = ["derive"] }
serde_json = "1.0.16"
validator = "0.14"
validator_derive = "0.14"

View File

@ -0,0 +1,27 @@
This is a contrived example intended to illustrate a few important Actix Web features.
*Imagine* that you have a process that involves 3 steps. The steps here
are dumb in that they do nothing other than call an HTTP endpoint that
returns the json that was posted to it. The intent here is to illustrate
how to chain these steps together as futures and return a final result
in a response.
Actix Web features illustrated here include:
1. handling json input param
2. validating user-submitted parameters using the 'validator' crate
2. `awc` client features:
- POSTing json body
3. chaining futures into a single response used by an asynch endpoint
### server
```bash
cd basics/json-validation
cargo run
# Started http server: 127.0.0.1:8080
```
Example query from the command line using httpie:
```echo '{"id":"1", "name": "JohnDoe"}' | http 127.0.0.1:8080/something```

View File

@ -0,0 +1,94 @@
// This is a contrived example intended to illustrate Actix Web features.
// *Imagine* that you have a process that involves 3 steps. The steps here
// are dumb in that they do nothing other than call an
// httpbin endpoint that returns the json that was posted to it. The intent
// here is to illustrate how to chain these steps together as futures and return
// a final result in a response.
//
// Actix Web features illustrated here include:
// 1. handling json input param
// 2. validating user-submitted parameters using the 'validator' crate
// 2. `awc` client features:
// - POSTing json body
// 3. chaining futures into a single response used by an async endpoint
use std::io;
use actix_web::{
error::ErrorBadRequest,
http::header::ContentType,
web::{self, BytesMut},
App, Error, HttpResponse, HttpServer,
};
use awc::Client;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use validator::Validate;
use validator_derive::Validate;
#[derive(Debug, Validate, Deserialize, Serialize)]
struct SomeData {
#[validate(length(min = 1, max = 1000000))]
id: String,
#[validate(length(min = 1, max = 100))]
name: String,
}
#[allow(dead_code)] // it is debug printed
#[derive(Debug, Deserialize)]
struct HttpBinResponse {
json: SomeData,
}
/// validate data, post json to httpbin, get it back in the response body, return deserialized
async fn step_x(data: SomeData, client: &Client) -> actix_web::Result<SomeData> {
// validate data
data.validate().map_err(ErrorBadRequest)?;
let mut res = client
.post("https://httpbin.org/post")
.send_json(&data)
.await
// <- convert SendRequestError to an InternalError, a type that implements the ResponseError trait
.map_err(actix_web::error::ErrorInternalServerError)?; // <- convert it into an actix_web::Error
let mut body = BytesMut::new();
while let Some(chunk) = res.next().await {
body.extend_from_slice(&chunk?);
}
let body: HttpBinResponse = serde_json::from_slice(&body).unwrap();
println!("{:?}", body);
Ok(body.json)
}
async fn create_something(
some_data: web::Json<SomeData>,
client: web::Data<Client>,
) -> Result<HttpResponse, Error> {
let some_data_2 = step_x(some_data.into_inner(), &client).await?;
let some_data_3 = step_x(some_data_2, &client).await?;
let d = step_x(some_data_3, &client).await?;
Ok(HttpResponse::Ok()
.content_type(ContentType::json())
.body(serde_json::to_string(&d).unwrap()))
}
#[actix_web::main]
async fn main() -> io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(|| {
App::new()
.app_data(web::Data::new(Client::default()))
.service(web::resource("/").route(web::post().to(create_something)))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}