Created
October 26, 2015 19:08
-
-
Save polachok/fc1f145fed1d7949066b to your computer and use it in GitHub Desktop.
hyper over unix socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use hyper::net::{NetworkStream,NetworkListener}; | |
use hyper::{Server}; | |
use hyper::server::Request; | |
use hyper::server::Response; | |
use hyper::server::Listening; | |
use hyper::net::Fresh; | |
use hyper; | |
use unix_socket::{UnixStream,UnixListener}; | |
use std::io; | |
use std::path::Path; | |
use std::io::{Read,Write}; | |
use std::net::{Ipv4Addr,SocketAddr,SocketAddrV4, ToSocketAddrs, TcpStream, TcpListener, Shutdown}; | |
use std::os::unix::io::{RawFd, AsRawFd, FromRawFd}; | |
pub struct UStream(UnixStream); | |
impl Clone for UStream { | |
fn clone(&self) -> UStream { | |
let fd = self.0.as_raw_fd(); | |
UStream(unsafe { UnixStream::from_raw_fd(fd) }) | |
} | |
} | |
impl NetworkStream for UStream { | |
fn peer_addr(&mut self) -> io::Result<SocketAddr> { | |
Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127,0,0,1), 1488))) | |
} | |
} | |
impl Read for UStream { | |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { | |
self.0.read(buf) | |
} | |
} | |
impl Write for UStream { | |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { | |
self.0.write(buf) | |
} | |
fn flush(&mut self) -> io::Result<()> { | |
self.0.flush() | |
} | |
} | |
pub struct HttpUnixListener(UnixListener); | |
impl Clone for HttpUnixListener { | |
fn clone(&self) -> HttpUnixListener { | |
let fd = self.0.as_raw_fd(); | |
HttpUnixListener(unsafe { UnixListener::from_raw_fd(fd) }) | |
} | |
} | |
impl HttpUnixListener { | |
pub fn new(path: &Path) -> io::Result<HttpUnixListener> { | |
Ok(HttpUnixListener(try!(UnixListener::bind(path)))) | |
} | |
} | |
impl NetworkListener for HttpUnixListener { | |
type Stream = UStream; | |
fn accept(&mut self) -> hyper::Result<UStream> { | |
match self.0.accept() { | |
Ok(us) => Ok(UStream(us)), | |
Err(e) => Err(hyper::Error::Io(e)), | |
} | |
} | |
fn local_addr(&mut self) -> io::Result<SocketAddr> { | |
Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127,0,0,1), 1488))) | |
} | |
} | |
fn hello(req: Request, res: Response<Fresh>) { | |
res.send(b"Hello World!").unwrap(); | |
} | |
pub fn new_server() -> Listening { | |
Server::new(HttpUnixListener::new(Path::new("/tmp/t.sock")).unwrap()).handle(hello).unwrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment