gdritter repos cg / master
Add ability to use Unix domain socket Getty Ritter 6 years ago
3 changed file(s) with 45 addition(s) and 7 deletion(s). Collapse all Expand all
1111 futures = "*"
1212 rustc-serialize = "*"
1313 lazy_static = "0.2"
14 tokio-core = "*"
15 tokio-io = "*"
16 unix_socket = "*"
77 Hyper(Error),
88 AddrParse(AddrParseError),
99 SQLite(::rusqlite::Error),
10 Env(::std::env::VarError),
11 IO(::std::io::Error),
1012 }
1113
1214 impl CGError {
1820 println!("Error parsing address: {}", err),
1921 &CGError::SQLite(ref err) =>
2022 println!("Error accessing db: {}", err),
23 &CGError::Env(ref err) =>
24 println!("Error reading env var: {}", err),
25 &CGError::IO(ref err) =>
26 println!("System I/O error: {}", err),
2127 }
2228 }
2329 }
3743 impl From<::rusqlite::Error> for CGError {
3844 fn from(err: ::rusqlite::Error) -> Self {
3945 CGError::SQLite(err)
46 }
47 }
48
49 impl From<::std::io::Error> for CGError {
50 fn from(err: ::std::io::Error) -> Self {
51 CGError::IO(err)
4052 }
4153 }
4254
66 extern crate time;
77 extern crate mustache;
88 extern crate rustc_serialize;
9 extern crate tokio_core;
10 extern crate tokio_io;
11 extern crate unix_socket;
912
1013 #[macro_use]
1114 extern crate lazy_static;
5457
5558 impl CG {
5659 fn main() -> Result<(), errors::CGError> {
57 let addr = "127.0.0.1:3000".parse()?;
58 let server = Http::new().bind(&addr, || {
59 let db = rusqlite::Connection::open("cocktails.db").unwrap();
60 Ok(CG { db })
61 })?;
62 println!("serving on {:?}", addr);
63 Ok(server.run()?)
60 match std::env::var("CG_UNIX_SOCK") {
61 Ok(addr) => {
62 std::fs::remove_file(&addr)?;
63 let mut socket = unix_socket::UnixListener::bind(addr)?;
64 let mut core = tokio_core::reactor::Core::new()?;
65 let http: Http = Http::new();
66 loop {
67 let db = rusqlite::Connection::open("cocktails.db")?;
68 core.run(
69 http.serve_connection(
70 tokio_io::io::AllowStdIo::new(socket.accept()?.0),
71 CG { db },
72 )
73 )?;
74 }
75 }
76
77 Err(_) => {
78 let addr = "127.0.0.1:3000".parse()?;
79 let server = Http::new().bind(&addr, || {
80 let db = rusqlite::Connection::open("cocktails.db").unwrap();
81 Ok(CG { db })
82 })?;
83 println!("serving on {:?}", addr);
84 Ok(server.run()?)
85 }
86 }
6487 }
6588
6689 fn route(&self, req: Request) -> Result<Page, errors::RuntimeError> {