Giter VIP home page Giter VIP logo

hyperlocal's Introduction

hyperlocal Build Status Coverage Status crates.io docs.rs Master API docs

hyper client and server bindings for unix domain sockets

Hyper is a rock solid rustlang HTTP client and server tool kit. Unix domain sockets provide a mechanism for host-local interprocess communication. Hyperlocal builds on and complements hyper's interfaces for building unix domain socket HTTP clients and servers.

This is useful for exposing simple HTTP interfaces for your Unix daemons in cases where you want to limit access to the current host, in which case, opening and exposing tcp ports is not needed. Examples of unix daemons that provide this kind of host local interface include, docker, a process container manager.

install

Add the following to your Cargo.toml file

[dependencies]
hyperlocal = "0.6"

usage

servers

A typical server can be built with hyperlocal::server::Server

extern crate hyper;
extern crate hyperlocal;
extern crate futures;

use std::fs;
use std::io;

use hyper::{header, Body, Request, Response};
use hyper::service::service_fn;

const PHRASE: &'static str = "It's a Unix system. I know this.";

fn hello(_: Request<Body>) -> impl futures::Future<Item = Response<Body>, Error = io::Error> + Send {
    futures::future::ok(
        Response::builder()
            .header(header::CONTENT_TYPE, "text/plain")
            .header(header::CONTENT_LENGTH, PHRASE.len() as u64)
            .body(PHRASE.into())
            .expect("failed to create response")
    )
}

fn run() -> io::Result<()> {
    let path = "test.sock";
    if let Err(err) = fs::remove_file("test.sock") {
        if err.kind() != io::ErrorKind::NotFound {
            return Err(err);
        }
    }
    let svr = hyperlocal::server::Server::new().bind(path, || service_fn(hello))?;
    println!("Listening on unix://{path} with 1 thread.", path = path);
    svr.run()?;
    Ok(())
}

fn main() {
    if let Err(err) = run() {
        eprintln!("error starting server: {}", err)
    }
}

clients

You can communicate over HTTP with Unix domain socket servers using hyper's Client interface. Configure your hyper client using Client::configure(...).

Hyper's client interface makes it easy to issue typical HTTP methods like GET, POST, DELETE with factory methods, get, post, delete, ect. These require an argument that can be tranformed into a hyper::Uri. Since unix domain sockets aren't represented with hostnames that resolve to ip addresses coupled with network ports ports, your standard url string won't do. Instead, use a hyperlocal::Uri which represents both file path to the domain socket and the resource uri path and query string.

extern crate futures;
extern crate hyper;
extern crate hyperlocal;
extern crate tokio_core;

use std::io::{self, Write};

use futures::Stream;
use futures::Future;
use hyper::{Client, rt};
use hyperlocal::{Uri, UnixConnector};

fn main() {
    let client = Client::builder()
        .keep_alive(false) // without this the connection will remain open
        .build::<_, ::hyper::Body>(UnixConnector::new());
    let url = Uri::new("test.sock", "/").into();

    let work = client
        .get(url)
        .and_then(|res| {
            println!("Response: {}", res.status());
            println!("Headers: {:#?}", res.headers());

            res.into_body().for_each(|chunk| {
                io::stdout().write_all(&chunk)
                    .map_err(|e| panic!("example expects stdout is open, error={}", e))
            })
        })
        .map(|_| {
            println!("\n\nDone.");
        })
        .map_err(|err| {
            eprintln!("Error {}", err);
        });

    rt::run(work);
}

Doug Tangren (softprops) 2015-2018

hyperlocal's People

Contributors

abronan avatar abusch avatar arsing avatar dylanmckay avatar gngeorgiev avatar mheese avatar mkocot avatar softprops avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.