Skip to content

Commit d9fcfa5

Browse files
committed
episode 1f http server
1 parent 96706f7 commit d9fcfa5

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from fastapi import FastAPI
2+
from fastapi.staticfiles import StaticFiles
3+
4+
app = FastAPI()
5+
6+
app.mount("/static", StaticFiles(directory="../static"), name="static")
7+
8+
9+
@app.get("/")
10+
@app.get("/hello/{name}")
11+
async def root(name: str = "World"):
12+
return {"message": f"Hello, {name}!"}
13+
14+
15+
@app.get("/items/{item_id}")
16+
async def read_item(item_id: int):
17+
return {"item_id": item_id}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[package]
2+
name = "warp_srv"
3+
version = "0.1.0"
4+
edition = "2018"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
serde_json = "1.0.64"
10+
tokio = { version = "1", features = ["full"] }
11+
warp = "0.3"
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use serde_json::json;
2+
use warp::Filter;
3+
4+
#[tokio::main]
5+
async fn main() {
6+
let directory = warp::path("static").and(warp::fs::dir("../../static/"));
7+
8+
let opt_name = warp::path::param::<String>()
9+
.map(Some)
10+
.or_else(|_| async {
11+
Ok::<(Option<String>,), std::convert::Infallible>((None,)) });
12+
let hello = warp::path("hello")
13+
.and(opt_name)
14+
.map(|name: Option<String>| {
15+
let msg = format!(
16+
"Hello, {}!",
17+
name.unwrap_or("World".to_string()));
18+
warp::reply::json(&json!({ "message": msg }))
19+
});
20+
let root = warp::path::end()
21+
.and(warp::get())
22+
.map(|| warp::reply::json(&json!({"message": "Hello, World?"})));
23+
24+
let items = warp::path!("items" / i32)
25+
.map(|id| warp::reply::json(&json!({ "item_id": id })));
26+
27+
let routes = directory.or(hello).or(items).or(root);
28+
29+
println!("Serving on localhost:3030");
30+
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
31+
}

1f_http_server/static/index.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<html>
2+
<body>Hello World!</body>
3+
</html>

0 commit comments

Comments
 (0)