Go net/http unix domain socket connection

10,269

Solution 1

You would have to implement your own RoundTripper to support unix sockets.

The easiest way is probably to just use http instead of unix sockets to communicate with docker.

Edit the init script and add -H tcp://127.0.0.1:xxxx, for example:

/usr/bin/docker -H tcp://127.0.0.1:9020

You can also just fake the dial function and pass it to the transport:

func fakeDial(proto, addr string) (conn net.Conn, err error) {
    return net.Dial("unix", sock)
}

tr := &http.Transport{
    Dial: fakeDial,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("http://d/test")

playground

There's only one tiny caveat, all your client.Get / .Post calls has to be a valid url (http://xxxx.xxx/path not unix://...), the domain name doesn't matter since it won't be used in connecting.

Solution 2

It's been a few years since this question was asked and answered, but I came across it while looking for the same thing. I also found the httpunix package which addresses this problem expertly.It also supports registering a new protocol so you can use native URLs such as http+unix://service-name/...... Worked quite nicely for me.

Share:
10,269
Matej
Author by

Matej

@matejkramny Hello, I am a Go, JS (node), PHP, Angular, JS, Java and Objective-C/Swift engineer. Email me on [email protected] LinkedIn: linkedin.com/in/matejkramny

Updated on July 19, 2022

Comments

  • Matej
    Matej almost 2 years

    I am having trouble connecting to my server, which listens on a Unix Domain Socket.

    Go's net/http package doesn't seem to be able to use socket paths to connect to a target.

    Is there a good alternative without having to create my own HTTP Protocol implementation using net?


    I found lots of solutions like these, but they are unsuitable

    I have tried:

    _, err := http.Get("unix:///var/run/docker.sock") (changing unix to path/socket. It always complains about an unsupported protocol