使用Go 1.5.1.
当我尝试向使用Basic Auth自动重定向到HTTPS的站点发出请求时,我期望得到301重定向响应,而不是得到401。
package main
import "net/http"
import "log"
func main() {
url := "http://aerolith.org/files"
username := "cesar"
password := "password"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("error", err)
}
if username != "" || password != "" {
req.SetBasicAuth(username, password)
log.Println("[DEBUG] Set basic auth to", username, password)
}
cli := &http.Client{
}
resp, err := cli.Do(req)
if err != nil {
log.Println("Do error", err)
}
log.Println("[DEBUG] resp.Header", resp.Header)
log.Println("[DEBUG] req.Header", req.Header)
log.Println("[DEBUG] code", resp.StatusCode)
}
注意curl返回301:
curl -vvv http://aerolith.org/files --user cesar:password
你知道哪里出错了吗?
对http://aerolith.org/files
的请求重定向到https://aerolith.org/files
(注意从http更改为https)。对https://aerolith.org/files
的请求重定向到https://aerolith.org/files/
(注意后面添加了/)。
Curl不遵循重定向。Curl打印从http://aerolith.org/files
重定向到https://aerolith.org/files/
的301状态。
Go客户端遵循两个重定向到https://aerolith.org/files/
。对https://aerolith.org/files/
的请求返回状态401,因为Go客户端没有通过重定向传播授权头。
Go客户端和Curl对https://aerolith.org/files/
的请求返回状态200。
如果你想跟随重定向并成功验证,在CheckRedirect函数中设置验证头:
cli := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
req.SetBasicAuth(username, password)
return nil
}}
resp, err := cli.Do(req)
如果你想匹配Curl所做的,直接使用传输。传输不遵循重定向。
resp, err := http.DefaultTransport.RoundTrip(req)
应用程序还可以使用客户端CheckRedirect功能和一个可区分的错误来防止重定向,如如何使Go HTTP客户端不自动遵循重定向的答案所示。这种技术似乎比较流行,但是比直接使用传输更复杂。
redirectAttemptedError := errors.New("redirect")
cli := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return redirectAttemptedError
}}
resp, err := cli.Do(req)
if urlError, ok := err.(*url.Error); ok && urlError.Err == redirectAttemptedError {
// ignore error from check redirect
err = nil
}
if err != nil {
log.Println("Do error", err)
}