diff options
| author | Aleksa Vuckovic <aleksa@vuckovic.cc> | 2024-08-14 07:45:43 +0200 |
|---|---|---|
| committer | Aleksa Vuckovic <aleksa@vuckovic.cc> | 2024-08-17 23:58:13 +0200 |
| commit | 021ca9b3601c1c9bf58b9c1aecc8bd7e0c7ed9b4 (patch) | |
| tree | b455017ccfa74c78d03c81a1e9863a0d30f25710 /src/main.rs | |
Diffstat (limited to 'src/main.rs')
| -rw-r--r-- | src/main.rs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..78133bd --- /dev/null +++ b/src/main.rs @@ -0,0 +1,57 @@ +use axum::{ + routing::{get, post}, + http::StatusCode, + Json, Router, +}; +use serde::{Deserialize, Serialize}; + +#[tokio::main] +async fn main() { + // initialize tracing + tracing_subscriber::fmt::init(); + + // build our application with a route + let app = Router::new() + // `GET /` goes to `root` + .route("/", get(root)) + // `POST /users` goes to `create_user` + .route("/users", post(create_user)); + + // run our app with hyper, listening globally on port 3000 + let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + axum::serve(listener, app).await.unwrap(); +} + +// basic handler that responds with a static string +async fn root() -> &'static str { + "Hello, World!" +} + +async fn create_user( + // this argument tells axum to parse the request body + // as JSON into a `CreateUser` type + Json(payload): Json<CreateUser>, +) -> (StatusCode, Json<User>) { + // insert your application logic here + let user = User { + id: 1337, + username: payload.username, + }; + + // 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 CreateUser { + username: String, +} + +// the output to our `create_user` handler +#[derive(Serialize)] +struct User { + id: u64, + username: String, +} |
