From 6a039f350ade4562fae6efb59335b2dadbb8e10b Mon Sep 17 00:00:00 2001 From: Mitchell Marino Date: Sun, 2 Apr 2023 16:52:17 -0500 Subject: [PATCH] switch to axum --- Cargo.toml | 10 +++- migrations/20230402213003_user.sql | 6 ++ src/main.rs | 91 +++++++++++++++++++++++++----- src/user.rs | 9 +++ 4 files changed, 99 insertions(+), 17 deletions(-) create mode 100644 migrations/20230402213003_user.sql create mode 100644 src/user.rs diff --git a/Cargo.toml b/Cargo.toml index 205f41f..7bbced4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,12 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rocket = "0.5.0-rc.2" +tokio = { version = "1.27", features = ["full"] } +axum = "0.6" sqlx = { version = "0.6", features = ["postgres", "runtime-tokio-rustls"] } -serde = "1.0" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } + + diff --git a/migrations/20230402213003_user.sql b/migrations/20230402213003_user.sql new file mode 100644 index 0000000..bb20d06 --- /dev/null +++ b/migrations/20230402213003_user.sql @@ -0,0 +1,6 @@ +CREATE TABLE users ( + id SERIAL PRIMARY KEY, + username varchar(255) NOT NULL, + password bytea +); + diff --git a/src/main.rs b/src/main.rs index f6e686f..821369e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,22 +1,83 @@ -#[macro_use] -extern crate rocket; +use axum::{ + http::StatusCode, + response::IntoResponse, + routing::{get, post}, + Extension, Json, Router, +}; +use serde::{Deserialize, Serialize}; +use sqlx::postgres::PgPoolOptions; +use sqlx::PgPool; +use std::net::SocketAddr; -use rocket::response::status::BadRequest; +#[tokio::main] +async fn main() { + // initialize tracing + tracing_subscriber::fmt::init(); -#[get("/event")] -fn events() -> String { - format!("event list") + PgPool::connect( + "postgresql://school_app_api_user:school_app_api_pass@localhost/school_app_api", + ); + + let db_url = std::env::var("DATABASE_URL") + .expect("Set `DATABASE_URL` to the url of the postgres database."); + + let pool = PgPoolOptions::new() + .max_connections(50) + .connect(&db_url) + .await + .context("could not connect to database_url")?; + + // build our application with a route + let app = Router::new() + // `GET /` goes to `root` + .route("/", get(root)) + // `POST /users` goes to `create_user` + .route("/user/signup", post(signup)) + .layer(Extension(pool)); + + // run our app with hyper + // `axum::Server` is a re-export of `hyper::Server` + let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); + tracing::info!("listening on {}", addr); + axum::Server::bind(&addr) + .serve(app.into_make_service()) + .await + .unwrap(); } -#[get("/event/")] -fn event_id(id: Result) -> Result> { - match id { - Ok(id) => Ok(format!("event for {}", id)), - Err(_) => Err(BadRequest(Some(format!("event id must be a valid u64")))), - } +// basic handler that responds with a static string +async fn root() -> &'static str { + "Hello, World!" } -#[launch] -fn rocket() -> _ { - rocket::build().mount("/", routes![events, event_id]) +async fn signup( + // this argument tells axum to parse the request body + // as JSON into a `CreateUser` type + Json(payload): Json, + Extension(pool): Extension, +) -> impl IntoResponse { + // insert your application logic here + sqlx::query!( + r#" + + "# + ); + + // this will be converted into a JSON response + // with a status code of `201 Created` + (StatusCode::CREATED, Json(user)) +} + +// the input to our `create_user` handler +#[derive(Deserialize)] +struct Signup { + username: String, + password: String, +} + +// the output to our `create_user` handler +#[derive(Serialize, sqlx::FromRow)] +struct User { + id: u64, + username: String, } diff --git a/src/user.rs b/src/user.rs new file mode 100644 index 0000000..e8da059 --- /dev/null +++ b/src/user.rs @@ -0,0 +1,9 @@ +use rocket::Route; + +pub fn routes() -> Vec { + routes![ + + ] +} + +