Go 中的基本 HTTP 认证

我尝试用下面的代码执行基本的 HTTP 身份验证,但它抛出了以下错误:

2013/05/2110:22:58获取 mydomain.example: 不支持的协议方案” 出口状态1

func basicAuth() string {
var username string = "foo"
var passwd string = "bar"
client := &http.Client{}
req, err := http.NewRequest("GET", "mydomain.example", nil)
req.SetBasicAuth(username, passwd)
resp, err := client.Do(req)
if err != nil{
log.Fatal(err)
}
bodyText, err := ioutil.ReadAll(resp.Body)
s := string(bodyText)
return s
}

知道我哪里做错了吗?

134458 次浏览

You need to specify the protocol for NewRequest, e.g. "http://", see here.

req, err := http.NewRequest("GET", "http://mydomain.example", nil)

the potential 'gotcha' is if your website does any redirects... Go-lang will drop your specified headers on the redirects. (I had to do wireshark to see this! You can quicky find out in chrome by right-clicking then "inspect element" and click network tab)

you'll want to define a redirect function that adds the header back in.

func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}


func redirectPolicyFunc(req *http.Request, via []*http.Request) error{
req.Header.Add("Authorization","Basic " + basicAuth("username1","password123"))
return nil
}


func main() {
client := &http.Client{
Jar: cookieJar,
CheckRedirect: redirectPolicyFunc,
}


req, err := http.NewRequest("GET", "http://localhost/", nil)
req.Header.Add("Authorization","Basic " + basicAuth("username1","password123"))
resp, err := client.Do(req)
}