Phlogger is a gopher server for Phlogs (Gopher Blogs)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.rs 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. extern crate config;
  2. use std::io::{Read, Write};
  3. use std::net::TcpListener;
  4. fn main() {
  5. let listener = TcpListener::bind(format!(
  6. "{domain}:{port}",
  7. domain = get_config_value("endpoint.address"),
  8. port = get_config_value("endpoint.port")
  9. ))
  10. .unwrap_or_else(|_| panic!("Listener could not be started!"));
  11. for connection in listener.incoming() {
  12. let mut handler = connection.unwrap();
  13. let mut buffer = [0; 2048];
  14. handler.read(&mut buffer).unwrap();
  15. let mut route = String::from_utf8_lossy(&buffer[..]).to_string();
  16. route = route[1..]
  17. .replace("\r", "")
  18. .replace("\n", "")
  19. .replace(" ", "")
  20. .trim_matches(char::from(0))
  21. .to_string();
  22. if route == "".to_string() {
  23. route = String::from("index")
  24. }
  25. let file = match std::fs::read_to_string(format!("static/public/{}", &route)) {
  26. Ok(body) => {
  27. println!(
  28. "Matched route /{uri} with file 'static/public/{uri}'",
  29. uri = &route
  30. );
  31. body
  32. }
  33. Err(_) => std::fs::read_to_string(format!("static/public/{}/index", &route))
  34. .unwrap_or_else(|_| String::from("Error: Page not found")),
  35. };
  36. let mut response: String = String::new();
  37. for line in file.lines() {
  38. let mut body: String = line.to_string();
  39. if line.chars().next().unwrap() == '0' || line.chars().next().unwrap() == '1' {
  40. body = line.replacen("/", "\t/", 1);
  41. }
  42. response = format!(
  43. "{ancestors}{body}\t{address}\t{port}\r\n",
  44. ancestors = response,
  45. body = body,
  46. address = get_config_value("endpoint.address"),
  47. port = get_config_value("endpoint.port")
  48. );
  49. }
  50. handler.write(response.as_bytes()).unwrap();
  51. handler.flush().unwrap();
  52. }
  53. }
  54. fn get_config_value(key: &str) -> String {
  55. let mut config = config::Config::default();
  56. config.merge(config::File::with_name("env.toml"));
  57. match config.get_str(key) {
  58. Ok(value) => value,
  59. Err(_) => {
  60. eprintln!("Config value '{}' not found", key);
  61. return String::from("");
  62. }
  63. }
  64. }