### usersテーブルの作成
sudo -u postgres psql CREATE TABLE users ( id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY, username text NOT NULL UNIQUE, password text NOT NULL );
axumでformでpostされたデータを受け取ります。
use axum::{Router, routing::get, routing::post, extract::Form};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
struct SignUp {
username: String,
password: String,
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", axum::routing::get(handle_index))
.route("/signup", axum::routing::post(handle_signup));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn handle_index()-> axum::response::Html<String> {
let tera = tera::Tera::new("templates/*").unwrap();
let mut context = tera::Context::new();
context.insert("title", "Index page");
context.insert("data", "hoge");
let output = tera.render("index.html", &context);
axum::response::Html(output.unwrap())
}
async fn handle_signup(form: Form<SignUp>)-> axum::response::Html<String> {
let signup: SignUp = form.0;
println!("{:?}", signup);
let tera = tera::Tera::new("templates/*").unwrap();
let mut context = tera::Context::new();
context.insert("title", "Index page");
context.insert("data", "hoge");
let output = tera.render("index.html", &context);
axum::response::Html(output.unwrap())
}
コマンドラインからPostします。
$ curl -X POST -d ‘username=山田太郎’ -d ‘password=asdf1234’ 127.0.0.1:3000/signup
Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.65s
Running `target/debug/login`
SignUp { username: “山田太郎”, password: “asdf1234” }
なるほど、なんとかここまでできた。ミドルウェアのところと、セッションの箇所をどうするか悩ましいが、まぁよしとしよう。