2019-06-17 05:37:14 +02:00
|
|
|
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
2019-06-13 00:14:10 +02:00
|
|
|
use serde::Deserialize;
|
2022-07-16 11:59:20 +02:00
|
|
|
use actix_web::web::{Either, Json, Form};
|
2019-06-13 00:14:10 +02:00
|
|
|
|
2023-01-09 10:52:42 +01:00
|
|
|
// <easy-form-handling>
|
2019-06-13 00:14:10 +02:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Register {
|
|
|
|
username: String,
|
|
|
|
country: String,
|
|
|
|
}
|
|
|
|
|
2022-07-16 11:59:20 +02:00
|
|
|
// register form is JSON
|
|
|
|
async fn json_register(form: web::Json<Register>) -> impl Responder {
|
|
|
|
format!("Hello {} from {}!", form.username, form.country)
|
|
|
|
}
|
|
|
|
|
|
|
|
// register form can be either JSON or URL-encoded
|
|
|
|
async fn register(form: Either<Json<Register>, Form<Register>>) -> impl Responder {
|
|
|
|
let Register { username, country } = form.into_inner();
|
|
|
|
format!("Hello {username} from {country}!")
|
|
|
|
}
|
|
|
|
// </easy-form-handling>
|
|
|
|
|
2019-12-28 17:24:52 +01:00
|
|
|
async fn index() -> HttpResponse {
|
2019-06-13 01:23:51 +02:00
|
|
|
HttpResponse::Ok()
|
2019-06-13 00:14:10 +02:00
|
|
|
.content_type("text/html; charset=utf-8")
|
2019-06-13 01:23:51 +02:00
|
|
|
.body(include_str!("../static/form.html"))
|
2019-06-13 00:14:10 +02:00
|
|
|
}
|
|
|
|
|
2020-09-12 17:21:54 +02:00
|
|
|
#[actix_web::main]
|
2019-12-28 17:24:52 +01:00
|
|
|
async fn main() -> std::io::Result<()> {
|
2019-06-13 00:14:10 +02:00
|
|
|
HttpServer::new(|| {
|
|
|
|
App::new()
|
|
|
|
.route("/", web::get().to(index))
|
|
|
|
.route("/register", web::post().to(register))
|
2022-07-16 11:59:20 +02:00
|
|
|
.route("/json_register", web::post().to(json_register))
|
2019-06-13 00:14:10 +02:00
|
|
|
})
|
2022-02-26 04:56:24 +01:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2019-06-13 00:14:10 +02:00
|
|
|
.run()
|
2019-12-28 17:24:52 +01:00
|
|
|
.await
|
2019-06-13 00:14:10 +02:00
|
|
|
}
|