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

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.

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

报告相同问题?

悬赏问题

  • ¥20 关于CMOS电路图的提问
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通
  • ¥15 关于c语言代码的问题
  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错