1
0
mirror of https://github.com/actix/actix-website synced 2024-11-28 02:22:57 +01:00
actix-website/examples/easy-form-handling/src/main.rs

42 lines
1.1 KiB
Rust
Raw Normal View History

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::Deserialize;
use actix_web::web::{Either, Json, Form};
// <easy-form-handling>
#[derive(Deserialize)]
struct Register {
username: String,
country: String,
}
// 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 {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(include_str!("../static/form.html"))
}
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<()> {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(index))
.route("/register", web::post().to(register))
.route("/json_register", web::post().to(json_register))
})
2022-02-26 04:56:24 +01:00
.bind(("127.0.0.1", 8080))?
.run()
2019-12-28 17:24:52 +01:00
.await
}