use serde::{Deserialize, Serialize};
use starlink::{error, event::LogEvent, info, init_logger, init_logger_with_auth, warn};
use std::{net::TcpListener, time::Duration};
use tinyhttp::prelude::*;
#[derive(Serialize, Deserialize, Debug)]
struct Event {
log: String,
}
#[post("/dev/log")]
fn log_route(req: Request) -> &'static str {
let headers = req.get_headers();
let Some(key) = headers.get("authorization") else {
eprintln!("No auth header");
return "INVALID AUTH KEY".into();
};
let Some(auth) = key.split_whitespace().nth(1) else {
eprintln!("Missing auth key");
return "INVALID AUTH KEY".into();
};
if auth != "mateo" {
eprintln!("Invalid auth key");
return "INVALID AUTH KEY".into();
}
let body = req.get_raw_body();
if let Ok(body) = serde_json::from_slice::<Vec<LogEvent<Event>>>(body) {
dbg!(&body);
for ev in body {
println!(
"{}{}: {:?}",
ev.tag
.map(|tag| format!("[{tag}] "))
.unwrap_or("".to_string()),
ev.level.as_ref().to_uppercase(),
ev.payload
);
}
} else {
eprintln!("invalid json value");
}
"GOT IT!"
}
fn start_server() {
if init_logger_with_auth("http://localhost:8008/dev/log", "mateo").is_err() {
return;
}
let socket = TcpListener::bind(":::8008").unwrap();
let conf = Config::new().routes(Routes::new(vec![log_route()]));
let http = HttpListener::new(socket, conf);
std::thread::spawn(move || {
http.start();
});
}
#[test]
fn test_basic_log() -> Result<(), Box<dyn std::error::Error>> {
start_server();
info!(
Event {
log: String::from("Hello!")
},
tag = String::from("TEST")
);
error!(Event {
log: String::from("NOOO")
});
std::thread::sleep(Duration::from_secs(3));
Ok(())
}