douyu7210 2015-07-31 22:48
浏览 361
已采纳

Golang:如何用表单请求模拟POST?

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条回答 默认 最新

  • doswy02440 2015-07-31 23:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?