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-03-09 21:08:08 -08:00
|
|
|
fn main() -> std::io::Result<()> {
|
|
|
|
HttpServer::new(|| {
|
|
|
|
App::new()
|
2019-03-26 04:29:00 +01:00
|
|
|
.data(AppState {
|
2019-03-09 21:08:08 -08:00
|
|
|
foo: "bar".to_string(),
|
|
|
|
})
|
2019-03-26 04:29:00 +01:00
|
|
|
.wrap(middleware::Logger::default())
|
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)))
|
|
|
|
.service(web::resource("/post3").route(web::post().to(handle_post_3)))
|
2019-03-09 18:03:09 -08:00
|
|
|
})
|
2019-03-09 21:08:08 -08:00
|
|
|
.bind("127.0.0.1:8080")?
|
|
|
|
.run()
|
2018-07-04 17:12:33 +02:00
|
|
|
}
|
|
|
|
|
2019-03-09 21:08:08 -08:00
|
|
|
fn index() -> Result<HttpResponse> {
|
|
|
|
Ok(HttpResponse::Ok()
|
2018-07-04 17:12:33 +02:00
|
|
|
.content_type("text/html; charset=utf-8")
|
|
|
|
.body(include_str!("../static/form.html")))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct MyParams {
|
|
|
|
name: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Simple handle POST request
|
2019-03-09 21:08:08 -08:00
|
|
|
fn handle_post_1(params: web::Form<MyParams>) -> Result<HttpResponse> {
|
|
|
|
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
|
|
|
|
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-03-09 21:08:08 -08:00
|
|
|
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
|
|
|
}
|