英文:
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")
只有一个小问题,你的所有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("unix", sock)
}
tr := &http.Transport{
Dial: fakeDial,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("http://d/test")
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论