回答

收藏

Go 中的基本 HTTP 身份验证

技术问答 技术问答 239 人阅读 | 0 人回复 | 2023-09-12

我正在尝试使用以下代码进行基本 HTTP 身份验证,但抛出以下错误:; w! e. k- I2 m. u
2013/05/21 10:22:58mydomain.com:不支持的协议方案“”退出状态 1( z1 n5 ~( ~0 `- a
    func basicAuth() string    var username string = "foo"    var passwd string = "bar"    client := &http.Client{}    req,err := http.NewRequest("GET","mydomain.com",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}  Q& z; t: e+ e) M
你知道我可能做错了什么吗?
6 s! d2 z' S; w/ I                                                                  b$ f2 g8 |$ \% U4 q5 o
    解决方案:                                                               
+ V3 |& W- s8 J- `                                                                潜在的问题是你的网站是否有任何重定向……Go-lang 在重定向时删除您指定的标头。(我必须使用它wireshark看到这一点!单击右键,然后检查元素,单击网络选项卡chrome中快速找到)- W0 U1 O3 j+ H
重新添加标头需要定义重定向函数。7 d4 E8 o  }. }+ G* {" D6 ^4 B
    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)}
    # A: `  d2 ~0 f  ?( t4 @
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则