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

227 lines
6.8 KiB
Rust
Raw Normal View History

2018-07-04 17:12:33 +02:00
#[macro_use]
extern crate serde_derive;
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,
}
2019-12-07 23:59:24 +06:00
#[actix_rt::main]
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)
})
.bind("127.0.0.1:8080")?
2019-12-07 23:59:24 +06:00
.start()
.await
2019-09-29 15:39:17 +03:00
}
fn app_config(config: &mut web::ServiceConfig) {
config.service(
web::scope("")
2019-03-26 04:29:00 +01:00
.data(AppState {
2019-03-09 21:08:08 -08:00
foo: "bar".to_string(),
})
.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>,
) -> HttpResponse {
HttpResponse::Ok().content_type("text/plain").body(format!(
"Your name is {}, and in AppState I have foo: {}",
params.name, state.foo
))
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::*;
2019-12-07 23:59:24 +06:00
use actix_web::body::{Body, ResponseBody};
2019-09-29 15:39:17 +03:00
use actix_web::dev::{HttpResponseBuilder, Service, ServiceResponse};
use actix_web::http::{header::CONTENT_TYPE, HeaderValue, StatusCode};
2019-12-07 23:59:24 +06:00
use actix_web::test::{self, TestRequest};
2019-09-29 15:39:17 +03:00
use actix_web::web::Form;
trait BodyTest {
fn as_str(&self) -> &str;
}
impl BodyTest for ResponseBody<Body> {
fn as_str(&self) -> &str {
match self {
ResponseBody::Body(ref b) => match b {
Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
_ => panic!(),
},
ResponseBody::Other(ref b) => match b {
Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),
_ => panic!(),
},
}
}
}
2019-12-07 23:59:24 +06:00
#[actix_rt::test]
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")
);
2019-12-07 23:59:24 +06:00
assert_eq!(resp.body().as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
2019-12-07 23:59:24 +06:00
#[actix_rt::test]
async fn handle_post_1_integration_test() {
let mut 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")
);
2019-12-07 23:59:24 +06:00
assert_eq!(resp.response().body().as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
2019-12-07 23:59:24 +06:00
#[actix_rt::test]
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();
let data = state
.app_data::<actix_web::web::Data<AppState>>()
2019-09-29 15:39:17 +03:00
.unwrap();
let params = Form(MyParams {
name: "John".to_string(),
});
let resp = handle_post_2(data.clone(), params).await;
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")
);
assert_eq!(
resp.body().as_str(),
"Your name is John, and in AppState I have foo: bar"
);
}
2019-12-07 23:59:24 +06:00
#[actix_rt::test]
async fn handle_post_2_integration_test() {
let mut 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")
);
assert_eq!(
resp.response().body().as_str(),
"Your name is John, and in AppState I have foo: bar"
);
}
2019-12-07 23:59:24 +06:00
#[actix_rt::test]
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;
let resp = match result.respond_to(&req).await {
2019-09-29 15:39:17 +03:00
Ok(t) => t,
2019-12-07 23:59:24 +06:00
Err(_) => {
HttpResponseBuilder::new(StatusCode::INTERNAL_SERVER_ERROR).finish()
}
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")
);
2019-12-07 23:59:24 +06:00
assert_eq!(resp.body().as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
2019-12-07 23:59:24 +06:00
#[actix_rt::test]
async fn handle_post_3_integration_test() {
let mut 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")
);
2019-12-07 23:59:24 +06:00
assert_eq!(resp.response().body().as_str(), "Your name is John");
2019-09-29 15:39:17 +03:00
}
}