Golang HTTP GET 请求返回 404

Dar*_*ren 6 curl get go

我正在尝试使用 BasicAuth 执行简单的 HTTP get。问题是响应不断返回“404”,尽管我可以将 URL 复制并粘贴到命令行 cURL 请求中并且工作正常:

const url string = "http://1.2.3.4:6710/REST/command"
const username string = "..."
const password string = "..."

fmt.Printf("\n%v\n", url)

client := &http.Client{}

req, _ := http.NewRequest("GET", url, nil)
req.SetBasicAuth(username, password)
req.Proto = "HTTP/1.0"
req.ProtoMinor = 0

resp, _ := client.Do(req)

fmt.Printf("\n%v\n", resp)

defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)   

fmt.Printf("\n%v\n\n", string(body))
Run Code Online (Sandbox Code Playgroud)

所以你可以看到我正在url立即打印出来 - 这是同一行文本,如果我将其复制到命令行 cURL 请求中,一切都会完美运行。

我的请求响应是

&{404 Not Found 404 HTTP/1.0 1 0 map[Pragma:[no-cache] Date:[Wed, 17 Apr 2013 15:01:33 GMT] Connection:[close] Server:[MoneyWorks_Datacentre/6.1.3 Win-x86 REST/6.1.3] Cache-Control:[no-store, no-cache, must-revalidate] Expires:[Wed, 17 Apr 2013 15:01:33 GMT]] 0xf8400e3920 -1 [] true map[] 0xf8400aa000}

golang 的 HTTP 函数有什么独特之处与 cURL 处理如此简单请求的方式不同吗?

编辑:我通过将 URL 传递给 来使其工作exec.Command("curl", url).Output()。显然这不是我希望的本机解决方案,但它目前有效。

Dar*_*ren 3

The issue was unicode-related. There was a %2F in my command (not displayed in my original question) that Go was converting to / that should have been left as %2F (cURL was properly leaving it as %2F). Changing the %2F to %252F fixed the issue.

看起来,当创建一个新的 HTTP 请求时,Go 会将你的 unicode 解析回纯文本,因此,如果你%3D在 URL 中提交给 HTTP 请求初始值设定项,它会将其转换为=. 我认为一个明显的解决方案是放入%253DURL 中,但显然 Go 中存在一个错误,它会转换%3D=,但不会%25转换为%. 我必须使用不透明 URL 请求 ( request.Url.Opaque) 来解决这个问题。