Matej
Matej

Reputation: 9835

Go net/http unix domain socket connection

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

Upvotes: 8

Views: 14937

Answers (2)

Nicholas
Nicholas

Reputation: 16066

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.

Upvotes: 4

OneOfOne
OneOfOne

Reputation: 99361

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.

Upvotes: 20

Related Questions