英文:
Golang: How to simulate a POST with a form request?
问题
我一直在搜索互联网,但几乎找不到关于在golang测试中发布表单的信息。这是我的尝试。然而,我遇到了错误"dial tcp: too many colons in address ::1"。如果我将地址更改为"http://localhost:8080/",我会得到"dial tcp 127.0.0.1:8080: connection refused"的错误。
我读到说,如果将(IPv6)地址放在方括号中,方括号会解决这个问题,但是然后我会得到错误"unrecognized protocol"。
var addr = "http://::1/"
h := handlers.GetHandler()
server := httptest.NewServer(h)
server.URL = addr
req, err := http.PostForm(addr+"login",
url.Values{"username": {"lemonparty"}, "password": {"bluewaffle"}})
if err != nil {
log.Fatal(err)
}
英文:
I've been scouring the internet and can't find much at all about posting forms in golang tests. This is my attempt at it. I get the error "dial tcp: too many colons in address ::1" though. If I change the address to "http://localhost:8080/" I get "dial tcp 127.0.0.1:8080: connection refused".
I've read that if you put the (IPv6) address in brackets, the brackets will fix the problem, but then I get the error unrecognized protocol.
var addr = "http://::1/"
h := handlers.GetHandler()
server := httptest.NewServer(h)
server.URL = addr
req, err := http.PostForm(addr+"login",
url.Values{"username": {"lemonparty"}, "password": {"bluewaffle"}})
if err != nil {
log.Fatal(err)
}
答案1
得分: 4
httptest.Server
中的Listener
不使用httptest.Server.URL
作为要监听的URL。它不关心该值是什么。它会监听本地主机上最低的可用端口号。
httptest.Server
上的URL属性实际上没有起到任何作用。你可以随意更改它,只是不要将请求发送到那里。可以参考这个示例程序https://play.golang.org/p/BsH38WLkrJ
基本上,如果我更改服务器的URL,然后将请求发送到我设置的值,它就不起作用,但如果我发送到默认值,它就可以正常工作。
还可以查看源代码http://golang.org/src/net/http/httptest/server.go?s=415:1018#L65,以及文件底部的证书;显然是硬编码为本地主机上最低的可用端口。如果你想向另一个URL发出请求,可以使用Listener
。
英文:
tl;dr the Listener
in httptest.Server
doesn't use the httptest.Server.URL
as the url to listen on. It doesn't care what that value is. It listens on local hosts lowest open port number.
The URL property on httptest.Server
is not really doing anything. Change it all you want, just don't send your requests there. Check out this example program https://play.golang.org/p/BsH38WLkrJ
Basically, if I change the servers URL then send the request to the value I set it to it doesn't work, but if I send it to the default value it does.
Also check out the source http://golang.org/src/net/http/httptest/server.go?s=415:1018#L65, as well as the certs at the bottom of the file; clearly hard coded for the lowest open port on local host. If you want to make request to another URL the Listener
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论