Share: go-vhost a library for name based virtual hosting

148 views
Skip to first unread message

Alan Shreve

unread,
Nov 9, 2013, 7:10:34 AM11/9/13
to golan...@googlegroups.com
Code: https://github.com/inconshreveable/go-vhost

It's a library that lets you implement custom name-based virtual-host like behavior for protocols that support it. You give it a connection and a protocol and it returns to you the hostname and a new connection object that works as if nothing had been read from the original connection.

An illustrative example:

conn, _ := l.Accept()
// reads out the ClientHello message and parses the hostname out of the SNI extension
newConn, err := vhost.TLS(conn)
// take different behaviors based on the hostname
switch newConn.Host() {
}

The intended audience is small, just people implementing their own servers/proxies. I needed it for more than one of my projects though so I split it out into a library in case anyone else could benefit.

Currently only HTTP and TLS are supported.

Alan Shreve

unread,
Dec 15, 2013, 12:23:53 AM12/15/13
to golan...@googlegroups.com
For anyone following this project, I've added a new higher-level interface for muxing connections which makes this library far easier to use. The high-level interface lets you wrap existing net.Listeners with "muxer" objects. You can then Listen() on a muxer for a particular virtual host name of interest which will return to you a net.Listener which only accepts connections with the given virtual host name.

Example code for an HTTP multiplexer:


    // listen for connections on a port
    l, _ := net.Listen(":80")

    // start multiplexing on it
    mux, _ := vhost.NewHTTPMuxer(l, muxTimeout)

    // use the default error handler
    go mux.HandleErrors()

    // listen for connections to different domains
    for _, v := range virtualHosts {
            vhost := v

            // vhost.Name is a virtual hostname like "foo.example.com"
            muxListener, _ := mux.Listen(vhost.Name)

            go func() {
                    for {
                            conn, _ := muxListener.Accept()
                            go vhost.Handle(conn)
                    }
            }()
    }

Code and docs: 


From: al...@inconshreveable.com
To: golan...@googlegroups.com
Subject: [go-nuts] Share: go-vhost a library for name based virtual hosting
Date: Sat, 9 Nov 2013 12:10:34 +0000
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
Reply all
Reply to author
Forward
0 new messages