initial commit; with baseline deps added

Signed-off-by: Erik Hollensbe <linux@hollensbe.org>
This commit is contained in:
Erik Hollensbe
2022-01-14 22:27:21 -08:00
commit ae9340276f
4 changed files with 78 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
/target
Cargo.lock
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "ratpack"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
hyper = { version = "*", features = [ "http1", "http2", "server", "runtime", "tcp", "stream" ] }
http = "*"
+58
View File
@@ -0,0 +1,58 @@
## http API idea
```rust
async fn root(req: Request) -> Result<Response, Error> {
Ok(Response::builder()
.status(StatusCode::OK)
.body("hello, world!")
.build()?)
}
async fn with_param(req: Request, params: Params) -> Result<Response, Error> {
let param = params.get("param")?;
Ok(Response::builder()
.status(StatusCode::OK)
.body(&format!("hello, {}!", param))
.build()?)
}
async fn with_param_post(req: Request, params: Params) -> Result<Response, Error> {
let param = params.get("param")?;
let body = req.body().await?; // should also support iter() probably for large requests
Ok(Response::builder()
.status(StatusCode::OK)
.body(&format!("hello, {}!\n{}\n", param, body))
.build()?)
}
#[derive(Clone, Debug)]
struct ToggleMiddleware {
state: AtomicBool,
}
#[async_trait]
impl Middleware for ToggleMiddleware {
async fn perform(
&mut self,
req: Request,
params: Params,
next: Next,
) -> Result<Response, Error> {
self.state.swap(self.state.get(), Ordering::Relaxed);
let response = next.call(req).await?;
let headers = response.headers_mut();
headers.insert("state", &format!("{:?}", self.state.get()));
Ok(response)
}
}
#[tokio::main]
async fn main() {
let mut app = Server::new();
app.with(ToggleMiddleware::new());
app.get("/", root);
app.get("/:param", with_param);
app.post("/:param", with_param_post);
app.listen("127.0.0.1:3000");
}
```
+8
View File
@@ -0,0 +1,8 @@
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}