Created
July 1, 2014 14:24
-
-
Save ulfurinn/45d94d8bcc99e0a10025 to your computer and use it in GitHub Desktop.
http over unix socket
This file contains 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
// A quick and dirty demo of talking HTTP over Unix domain sockets | |
package main | |
import ( | |
"fmt" | |
"io" | |
"net" | |
"net/http" | |
"os" | |
"strings" | |
"time" | |
"github.com/codegangsta/martini" | |
) | |
type unixDialer struct { | |
net.Dialer | |
} | |
// overriding net.Dialer.Dial to force unix socket connection | |
func (d *unixDialer) Dial(network, address string) (net.Conn, error) { | |
parts := strings.Split(address, ":") | |
return d.Dialer.Dial("unix", parts[0]) | |
} | |
// copied from http.DefaultTransport with minimal changes | |
var transport http.RoundTripper = &http.Transport{ | |
Proxy: http.ProxyFromEnvironment, | |
Dial: (&unixDialer{net.Dialer{ | |
Timeout: 30 * time.Second, | |
KeepAlive: 30 * time.Second, | |
}, | |
}).Dial, | |
TLSHandshakeTimeout: 10 * time.Second, | |
} | |
func main() { | |
m := martini.Classic() | |
m.Get("/demo", handler) | |
listener, err := net.Listen("unix", "http.sock") | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
go http.Serve(listener, m) // http.Serve takes any net.Listener implementation | |
time.Sleep(1000 * time.Millisecond) | |
c := http.Client{} | |
c.Transport = transport // use the unix dialer | |
resp, err := c.Get("http://http.sock/demo") | |
if err != nil { | |
fmt.Println(err.Error()) | |
return | |
} | |
io.Copy(os.Stdout, resp.Body) | |
} | |
func handler() (code int, body string) { | |
code = 200 | |
body = "ok" | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment