8

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

1
  • You might find this link usefule: gist.github.com/teknoraver/5ffacb8757330715bcbcc90e6d46ac74 This is HTTP client and server implementation someone wrote, I checked it and it works fine, just do small changes like changing the name of the socket to /var/run/socket.sock. Commented Aug 6, 2020 at 13:23

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@matejkramny I added a tip about just using http instead.
Awesome! I was going to point out you can register a protocol implementation (golang.org/pkg/net/http/#Transport.RegisterProtocol), but this is way easier! Thx
@matejkramny using RegisterProtocol you'd have to pretty much copy/paste DefaultTransport.RoundTrip and modify it to use unix.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.