fmt::Display implemented for Threads and Posts

doctorpavel
Dawid J. Kubis 3 years ago
parent 172dba215a
commit 7e7c0e2173

@ -7,7 +7,7 @@ use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::str;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, MutexGuard};
use lazy_static::lazy_static;
use structopt::StructOpt;
@ -32,17 +32,22 @@ struct Opt {
max_posts: usize,
}
// get command line arguments and make them static
// safe because they're read-only
lazy_static! {
// first parse command line arguments
static ref OPT: Opt = Opt::from_args();
}
#[derive(Debug)]
struct Cache<'a>(&'a str);
// TODO cache
//#[derive(Debug)]
//struct Cache<'a>(&'a str);
fn handle(request: Request, database: Arc<Mutex<sled::Db>>) -> &'static str {
let database = database.lock().unwrap();
fn handle(request: Request) -> &'static str {
match request.method.as_str() {
"GET" => get(&request.uri),
"GET" => get(&request.uri, database),
"POST" => "HTTP/1.1 200 OK",
// check admin hash
"DELETE" => "HTTP/1.1 200 OK",
@ -50,11 +55,11 @@ fn handle(request: Request) -> &'static str {
}
}
fn get(path: &str) -> &'static str {
fn get(path: &str, database: MutexGuard<sled::Db>) -> &'static str {
match path {
// list threads in this case
"/" => dbg!(INDEX),
// list posts here
// list specific thread here
s => "",
}
}
@ -66,13 +71,14 @@ fn main() {
// create threadpool for incoming requests
let pool = ThreadPool::new(num_cpus::get());
// open database
let db = sled::open(&OPT.database).unwrap();
// setup cache
let cache = Arc::new(Cache(""));
let db = Arc::new(Mutex::new(sled::open(&OPT.database).unwrap()));
// TODO setup cache
//let cache = Arc::new(Cache(""));
// wait for requests
for stream in listener.incoming() {
let mut stream = stream.unwrap();
let database = Arc::clone(&db);
pool.execute(move || {
let ip = stream.peer_addr();
// TODO check if valid ip before reading request
@ -87,7 +93,7 @@ fn main() {
// handle request
// add database and cache here
stream.write(handle(request).as_bytes()).unwrap();
stream.write(handle(request, database).as_bytes()).unwrap();
});
}
}

@ -1,6 +1,35 @@
struct Post {
ip: [u8; 4],
code: u64,
date: String,
body: String,
use std::fmt;
#[derive(Debug, Clone)]
pub struct Post {
pub id: u64,
pub ip: [u8; 4],
pub date: String,
pub body: String,
}
impl fmt::Display for Post {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"<article><div><span class=\"info\">{} {}</span></div><p>{}</p></article>",
self.id, self.date, self.body,
)
}
}
pub struct Thread {
pub id: u64,
pub topic: String,
pub posts: Vec<Post>,
}
impl fmt::Display for Thread {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let posts: String = self
.posts
.iter()
.fold(String::from(""), |a, b| format!("{}{}", a, b));
write!(f, "{}", posts)
}
}

@ -17,190 +17,3 @@
</head>
</html>

Loading…
Cancel
Save