feat: mini http server built on hyper which throws back json

This commit is contained in:
əlemi 2022-10-09 01:46:57 +02:00
commit 0706bfc420
5 changed files with 92 additions and 0 deletions

10
.editorconfig Normal file
View file

@ -0,0 +1,10 @@
# Default to Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = tab
indent_size = 4
[*.rs]
indent_size = 2

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

1
.rustfmt.toml Normal file
View file

@ -0,0 +1 @@
use_tabs = true

14
Cargo.toml Normal file
View file

@ -0,0 +1,14 @@
[package]
name = "http-debugger"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bytes = "1"
http-types = "2"
hyper = { version = "0.14", features = ["full"] }
tokio = { version = "1", features = ["full"] }
pretty_env_logger = "0.4"
serde = "1"
serde_json = "1"

66
src/main.rs Normal file
View file

@ -0,0 +1,66 @@
use std::collections::HashMap;
use std::net::SocketAddr;
use hyper::http::HeaderValue;
use hyper::server::conn::Http;
use hyper::service::service_fn;
use hyper::{Request, Response, Body};
use tokio::net::TcpListener;
use serde::Serialize;
fn str_or_repr(v: &HeaderValue) -> String {
match v.to_str() {
Ok(str) => {
str.to_string()
},
Err(e) => {
format!("{:?} ({})", v, e)
},
}
}
#[derive(Serialize)]
struct InspectRequest {
pub host: String,
pub method: String,
pub headers: HashMap<String, String>,
pub body: Option<String>,
pub version: String,
}
async fn hello(req: Request<Body>) -> Result<Response<Body>, serde_json::error::Error> {
let response = InspectRequest {
host: req.uri().to_string(),
method: req.method().to_string(),
version: format!("{:?}", req.version()),
headers: req.headers().iter().map(|x| (x.0.to_string(), str_or_repr(x.1))).collect(),
body: Some(format!("{:?}", req.body())),
};
println!(" * {}", serde_json::to_string_pretty(&response)?);
Ok(Response::new(serde_json::to_string(&response)?.into()))
}
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
pretty_env_logger::init();
let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
let listener = TcpListener::bind(addr).await?;
println!("Listening on http://{}", addr);
loop {
let (stream, _) = listener.accept().await?;
tokio::task::spawn(async move {
if let Err(err) = Http::new()
.serve_connection(stream, service_fn(hello))
.await
{
println!("Error serving connection: {:?}", err);
}
});
}
}