This repository has been archived by the owner on Jul 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.rs
86 lines (69 loc) · 1.85 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::net::SocketAddr;
use axum::{response::IntoResponse, routing::get, Json, Router};
use serde::Serialize;
#[derive(Serialize)]
struct Todo {
id: usize,
task: String,
done: bool,
}
impl Todo {
fn new(id: usize, task: &'static str) -> Self {
Self {
id,
task: String::from(task),
done: false,
}
}
}
async fn todos() -> impl IntoResponse {
let todos: Vec<Todo> = vec![Todo::new(
1,
"convert all my GitHub Actions pipelines to Nix",
)];
Json(todos)
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
axum::Server::bind(&addr)
.serve(app().into_make_service())
.await
.unwrap();
}
fn app() -> Router {
Router::new().route("/todos", get(todos))
}
#[cfg(test)]
mod tests {
use std::net::TcpListener;
use hyper::{Body, Request};
use super::*;
// Not an awesome test but it gets the job done for demo purposes
#[tokio::test]
async fn todos_endpoint() {
let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
let listener = TcpListener::bind(addr).unwrap();
tokio::spawn(async move {
axum::Server::from_tcp(listener)
.unwrap()
.serve(app().into_make_service())
.await
.unwrap();
});
let client = hyper::Client::new();
let response = client
.request(
Request::builder()
.method(hyper::Method::GET)
.uri(format!("http://{}/todos", addr))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let code = response.status();
assert_eq!(code, hyper::StatusCode::OK);
}
}