Run like:
# run server
go run main.go
In another terminal:
$ export DOCKER_HOST=tcp://localhost:8080
# run whatever docker commands:
$ docker ps
$ docker build .
And you'll see all the traffic in the other terminal window.
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"time" | |
) | |
type unixDialer struct { | |
net.Dialer | |
} | |
// overriding net.Dialer.Dial to force unix socket connection | |
func (d *unixDialer) Dial(network, address string) (net.Conn, error) { | |
return d.Dialer.Dial("unix", "/var/run/docker.sock") | |
} | |
type loggingListener struct { | |
net.Listener | |
} | |
func (l *loggingListener) Accept() (net.Conn, error) { | |
conn, err := l.Listener.Accept() | |
if err != nil { | |
return nil, err | |
} | |
return &loggingConn{Conn: conn}, nil | |
} | |
type loggingConn struct { | |
net.Conn | |
} | |
func (c *loggingConn) Read(b []byte) (int, error) { | |
n, err := c.Conn.Read(b) | |
if err != nil { | |
return n, err | |
} | |
fmt.Printf("Read %d bytes: %s\n", n, string(b[:n])) | |
return n, err | |
} | |
func (c *loggingConn) Write(b []byte) (int, error) { | |
n, err := c.Conn.Write(b) | |
if err != nil { | |
return n, err | |
} | |
fmt.Printf("Wrote %d bytes: %s\n", n, string(b[:n])) | |
return n, err | |
} | |
func main() { | |
u, err := url.Parse("http://docker") | |
if err != nil { | |
log.Panicln(err) | |
} | |
proxy := httputil.NewSingleHostReverseProxy(u) | |
proxy.Transport = &http.Transport{ | |
Proxy: http.ProxyFromEnvironment, | |
Dial: (&unixDialer{net.Dialer{ | |
Timeout: 30 * time.Second, | |
KeepAlive: 30 * time.Second, | |
}, | |
}).Dial, | |
TLSHandshakeTimeout: 10 * time.Second, | |
} | |
listener, err := net.Listen("tcp", ":8080") | |
if err != nil { | |
log.Panicln(err) | |
} | |
loggingListener := &loggingListener{Listener: listener} | |
http.Serve(loggingListener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println(r) | |
proxy.ServeHTTP(w, r) | |
})) | |
} |