gpt4 book ai didi

go - Go 中的基本 HTTP 身份验证

转载 作者:IT老高 更新时间:2023-10-28 12:59:04 28 4
gpt4 key购买 nike

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

2013/05/21 10:22:58 Get mydomain.example: unsupported protocol scheme ""exit status 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
}

知道我做错了什么吗?

最佳答案

潜在的“问题”是如果您的网站进行任何重定向... Go-lang 会将您指定的 header 放在重定向上。 (我必须做wireshark才能看到这个!您可以通过右键单击然后“检查元素”并单击网络选项卡在chrome中快速找到)

您需要定义一个重定向函数,将 header 重新添加进去。

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)
}

关于go - Go 中的基本 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673766/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com