diff options
| author | mo khan <mo@mokhan.ca> | 2025-05-29 16:33:49 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-05-29 16:33:49 -0600 |
| commit | 7fe231a39484858a9f2268f76c675cb41e8629bd (patch) | |
| tree | 8710e59121e34b9aeb186f6a204df3036a62f1da /src/server.rs | |
| parent | 14104f967a2c60d382bb3c8a0c74e99a163b6f69 (diff) | |
chore: move server to a separate file
Diffstat (limited to 'src/server.rs')
| -rw-r--r-- | src/server.rs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..709aba1 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,41 @@ +use std::fs; +use std::io::BufReader; +use std::io::prelude::*; +use std::net::TcpListener; +use std::net::TcpStream; + +pub struct Server { + bind: String, +} + +impl Server { + pub fn new(bind: String) -> Server { + Server { bind } + } + + pub fn start(&self) { + let listener = TcpListener::bind(self.bind.clone()).unwrap(); + for next_stream in listener.incoming() { + self.handle(next_stream.unwrap()); + } + } + + pub fn handle(&self, mut stream: TcpStream) { + let io = BufReader::new(&stream); + let request_line = io.lines().next().unwrap().unwrap(); + + let (status_line, filename) = match &request_line[..] { + "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "./public/index.html"), + "GET /.well-known/oauth-authorization-server HTTP/1.1" => { + ("HTTP/1.1 200 OK", "./public/metadata.json") + } + _ => ("HTTP/1.1 404 NOT FOUND", "./public/404.html"), + }; + + let contents = fs::read_to_string(filename).unwrap(); + let length = contents.len(); + let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); + + stream.write_all(response.as_bytes()).unwrap(); + } +} |
