1
0
mirror of https://github.com/actix/examples synced 2025-02-02 17:39:05 +01:00

220 lines
6.7 KiB
Rust
Raw Normal View History

use serde::{Deserialize, Serialize};
2018-07-04 17:12:33 +02:00
use actix_web::{
2019-03-09 21:08:08 -08:00
middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result,
2018-07-04 17:12:33 +02:00
};
struct AppState {
foo: String,
}
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2019-12-07 23:59:24 +06:00
async fn main() -> std::io::Result<()> {
2019-03-09 21:08:08 -08:00
HttpServer::new(|| {
App::new()
2019-09-29 15:39:17 +03:00
.wrap(middleware::Logger::default())
.configure(app_config)
})
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
2019-12-25 20:48:33 +04:00
.run()
2019-12-07 23:59:24 +06:00
.await
2019-09-29 15:39:17 +03:00
}
fn app_config(config: &mut web::ServiceConfig) {
config.service(
web::scope("")
2022-01-29 15:23:37 +00:00
.app_data(web::Data::new(AppState {
2019-03-09 21:08:08 -08:00
foo: "bar".to_string(),
2022-01-29 15:23:37 +00:00
}))
2019-03-09 21:08:08 -08:00
.service(web::resource("/").route(web::get().to(index)))
.service(web::resource("/post1").route(web::post().to(handle_post_1)))
.service(web::resource("/post2").route(web::post().to(handle_post_2)))
2019-12-07 23:59:24 +06:00
.service(web::resource("/post3").route(web::post().to(handle_post_3))),
2019-09-29 15:39:17 +03:00
);
2018-07-04 17:12:33 +02:00
}
2019-12-07 23:59:24 +06:00
async fn index() -> Result<HttpResponse> {
2019-03-09 21:08:08 -08:00
Ok(HttpResponse::Ok()
2018-07-04 17:12:33 +02:00
.content_type("text/html; charset=utf-8")
.body(include_str!("../static/form.html")))
}
2019-09-29 15:39:17 +03:00
#[derive(Serialize, Deserialize)]
2018-07-04 17:12:33 +02:00
pub struct MyParams {
name: String,
}
/// Simple handle POST request
2019-12-07 23:59:24 +06:00
async fn handle_post_1(params: web::Form<MyParams>) -> Result<HttpResponse> {
2019-03-09 21:08:08 -08:00
Ok(HttpResponse::Ok()
2018-07-04 17:12:33 +02:00
.content_type("text/plain")
.body(format!("Your name is {}", params.name)))
}
/// State and POST Params
2019-12-07 23:59:24 +06:00
async fn handle_post_2(
2019-03-16 20:23:09 -07:00
state: web::Data<AppState>,
2019-03-09 21:08:08 -08:00
params: web::Form<MyParams>,
2022-01-29 15:23:37 +00:00
) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().content_type("text/plain").body(format!(
2019-03-09 21:08:08 -08:00
"Your name is {}, and in AppState I have foo: {}",
params.name, state.foo
2022-01-29 15:23:37 +00:00
)))
2018-07-04 17:12:33 +02:00
}
/// Request and POST Params
2019-12-07 23:59:24 +06:00
async fn handle_post_3(req: HttpRequest, params: web::Form<MyParams>) -> impl Responder {
2018-07-04 17:12:33 +02:00
println!("Handling POST request: {:?}", req);
2019-03-09 21:08:08 -08:00
HttpResponse::Ok()
2018-07-04 17:12:33 +02:00
.content_type("text/plain")
2019-03-09 21:08:08 -08:00
.body(format!("Your name is {}", params.name))
2018-07-04 17:12:33 +02:00
}
2019-09-29 15:39:17 +03:00
#[cfg(test)]
mod tests {
use super::*;
2022-01-29 15:23:37 +00:00
use actix_web::body::to_bytes;
use actix_web::dev::{Service, ServiceResponse};
use actix_web::http::{header::HeaderValue, header::CONTENT_TYPE, StatusCode};
2019-12-07 23:59:24 +06:00
use actix_web::test::{self, TestRequest};
2022-01-29 15:23:37 +00:00
use actix_web::web::{Bytes, Form};
2019-09-29 15:39:17 +03:00
trait BodyTest {
fn as_str(&self) -> &str;
}
2022-01-29 15:23:37 +00:00
impl BodyTest for Bytes {
2019-09-29 15:39:17 +03:00
fn as_str(&self) -> &str {
2022-01-29 15:23:37 +00:00
std::str::from_utf8(self).unwrap()
2019-09-29 15:39:17 +03:00
}
}
2022-01-29 15:23:37 +00:00
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn handle_post_1_unit_test() {
2019-09-29 15:39:17 +03:00
let params = Form(MyParams {
name: "John".to_string(),
});
2019-12-07 23:59:24 +06:00
let resp = handle_post_1(params).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain")
);
2022-01-29 15:23:37 +00:00
let body = to_bytes(resp.into_body()).await.unwrap();
assert_eq!(body.as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
2022-01-29 15:23:37 +00:00
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn handle_post_1_integration_test() {
2022-01-29 15:23:37 +00:00
let app = test::init_service(App::new().configure(app_config)).await;
2019-09-29 15:39:17 +03:00
let req = test::TestRequest::post()
.uri("/post1")
2019-12-07 23:59:24 +06:00
.set_form(&MyParams {
name: "John".to_string(),
})
2019-09-29 15:39:17 +03:00
.to_request();
2019-12-07 23:59:24 +06:00
let resp: ServiceResponse = app.call(req).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain")
);
2022-01-29 15:23:37 +00:00
let body = to_bytes(resp.into_body()).await.unwrap();
assert_eq!(body.as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
2022-01-29 15:23:37 +00:00
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn handle_post_2_unit_test() {
2019-09-29 15:39:17 +03:00
let state = TestRequest::default()
.data(AppState {
foo: "bar".to_string(),
})
.to_http_request();
2019-12-25 20:48:33 +04:00
let data = state.app_data::<actix_web::web::Data<AppState>>().unwrap();
2019-09-29 15:39:17 +03:00
let params = Form(MyParams {
name: "John".to_string(),
});
2022-01-29 15:23:37 +00:00
let resp = handle_post_2(data.clone(), params).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain")
);
2022-01-29 15:23:37 +00:00
let body = to_bytes(resp.into_body()).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(
2022-01-29 15:23:37 +00:00
body.as_str(),
2019-09-29 15:39:17 +03:00
"Your name is John, and in AppState I have foo: bar"
);
}
2022-01-29 15:23:37 +00:00
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn handle_post_2_integration_test() {
2022-01-29 15:23:37 +00:00
let app = test::init_service(App::new().configure(app_config)).await;
2019-09-29 15:39:17 +03:00
let req = test::TestRequest::post()
.uri("/post2")
2019-12-07 23:59:24 +06:00
.set_form(&MyParams {
name: "John".to_string(),
})
2019-09-29 15:39:17 +03:00
.to_request();
2019-12-07 23:59:24 +06:00
let resp: ServiceResponse = app.call(req).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain")
);
2022-01-29 15:23:37 +00:00
let resp = resp.into_parts().1;
let body = to_bytes(resp.into_body()).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(
2022-01-29 15:23:37 +00:00
body.as_str(),
2019-09-29 15:39:17 +03:00
"Your name is John, and in AppState I have foo: bar"
);
}
2022-01-29 15:23:37 +00:00
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn handle_post_3_unit_test() {
2019-09-29 15:39:17 +03:00
let req = TestRequest::default().to_http_request();
let params = Form(MyParams {
name: "John".to_string(),
});
2019-12-07 23:59:24 +06:00
let result = handle_post_3(req.clone(), params).await;
2022-01-29 15:23:37 +00:00
let resp = result.respond_to(&req);
2019-09-29 15:39:17 +03:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain")
);
2022-01-29 15:23:37 +00:00
let body = match to_bytes(resp.into_body()).await {
Ok(x) => x,
_ => panic!(),
};
assert_eq!(body.as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
2022-01-29 15:23:37 +00:00
#[actix_web::test]
2019-12-07 23:59:24 +06:00
async fn handle_post_3_integration_test() {
2022-01-29 15:23:37 +00:00
let app = test::init_service(App::new().configure(app_config)).await;
2019-09-29 15:39:17 +03:00
let req = test::TestRequest::post()
.uri("/post3")
2019-12-07 23:59:24 +06:00
.set_form(&MyParams {
name: "John".to_string(),
})
2019-09-29 15:39:17 +03:00
.to_request();
2019-12-07 23:59:24 +06:00
let resp: ServiceResponse = app.call(req).await.unwrap();
2019-09-29 15:39:17 +03:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain")
);
2022-01-29 15:23:37 +00:00
let body = to_bytes(resp.into_body()).await.unwrap();
assert_eq!(body.as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
}