使用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知道会出什么问题吗?
发布于 2015-09-24 05:17:17
对http://aerolith.org/files的请求重定向到https://aerolith.org/files (注意从http更改为https)。对https://aerolith.org/files的请求重定向到https://aerolith.org/files/ (注意尾/的添加)。
卷曲不跟随重定向。Curl打印从http://aerolith.org/files重定向到https://aerolith.org/files/的301状态。
Go客户端遵循两个重定向到https://aerolith.org/files/。对https://aerolith.org/files/的请求返回状态401,因为Go客户端不通过重定向传播授权头。
从Go客户端对https://aerolith.org/files/的请求和Curl返回状态200。
如果要成功地执行重定向和auth,请在CheckRedirect函数中设置auth标头:
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)
}https://stackoverflow.com/questions/32751065
复制相似问题