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

65 lines
1.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-03-09 21:08:08 -08:00
fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.state(AppState {
foo: "bar".to_string(),
})
.middleware(middleware::Logger::default())
.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-09 21:08:08 -08:00
state: web::State<AppState>,
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
}