Go net/http unix domain socket连接

huangapple go评论81阅读模式
英文:

Go net/http unix domain socket connection

问题

我遇到了连接到监听在Unix域套接字上的服务器的问题。

Go的net/http包似乎无法使用套接字路径连接到目标。

有没有一个好的替代方法,而不必使用net创建自己的HTTP协议实现?


我找到了很多解决方案,比如这些,但它们都不适用。

我尝试过:

_, err := http.Get("unix:///var/run/docker.sock")(将unix更改为path/socket)。它总是抱怨不支持的协议。

英文:

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

得分: 20

你需要实现自己的RounTripper来支持unix套接字。最简单的方法可能是改用http而不是unix套接字与docker进行通信。

编辑init脚本并添加-H tcp://127.0.0.1:xxxx,例如:

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

你也可以伪造dial函数并将其传递给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

只有一个小问题,你的所有client.Get / .Post调用必须是有效的URL(http://xxxx.xxx/path而不是unix://...),域名无关紧要,因为它不会用于连接。

英文:

<strike>You would have to implement your own RoundTripper to support unix sockets.</strike>

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(&quot;unix&quot;, sock)
}

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

<kbd>playground</kbd>

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.

答案2

得分: 3

这个问题已经问答了几年了,但我在寻找同样的东西时遇到了它。我还找到了名为httpunix的包,它能很好地解决这个问题。它还支持注册新的协议,这样你就可以使用本地的URL,比如http+unix://service-name/.....。对我来说效果非常好。

英文:

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.

huangapple
  • 本文由 发表于 2014年10月7日 03:53:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/26223839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定