经过认证的来自golang的http客户端请求 [英] authenticated http client requests from golang

查看:118
本文介绍了经过认证的来自golang的http客户端请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

 客户端:=& http.Client {} 

/ *认证* /
req,err:= http.NewRequest(GET,http://164.99.113.32/Authenticate,nil)
req.SetBasicAuth(< username> ,< password>)
resp,err:= client.Do(req)
if err!= nil {
fmt.Printf(Error:%s,err )
}

/ *获取详细信息* /
req.URL,_ = url.Parse(http://164.99.113.32/Details)
resp,err = client.Do(req)
if err!= nil {
fmt.Printf(Error:%s,err)
}

现在,第二个http调用失败,出现401访问被拒绝错误。一个不同的REST客户端(一个Firefox插件)正确地从服务器获取细节信息,所以我知道服务器端没有任何问题。我需要传递某种类型的会话字符串还是我们在前一个请求中获得的内容? 好的。我解决了这个问题。我只需要创建一个cookie jar。



我很惊讶这不会被默认的golang http
req / client类处理。



我必须使用的代码是:

  type myjar struct {
jar map [string] [] * http.Cookie
}

func(p * myjar)SetCookies(u * url.URL,cookies [] * http.Cookie){
fmt.Printf(URL是:%s\\\
,u.String())
fmt.Printf(正在设置的cookie是:%s\\\
,cookies)
p.jar [u.Host] = cookies
}

func(p * myjar)Cookies(u * url.URL)[] * http.Cookie {
fmt.Printf(URL是:%s\\\
,u.String())
fmt.Printf(返回的Cookie是:%s\\\
,p.jar [u .Host])
return p.jar [u.Host]
}

然后在main:

  jar:=& myjar {} 
jar.jar = make(map [字符串] [] * http.Cookie)
client.Jar = jar

Works。


I have the following code:

client := &http.Client{}

/* Authenticate */
req, err := http.NewRequest("GET", "http://164.99.113.32/Authenticate", nil)
req.SetBasicAuth("<username>","<password>")
resp, err := client.Do(req)
if err != nil {
    fmt.Printf("Error : %s", err)
}

/* Get Details */
req.URL, _ = url.Parse("http://164.99.113.32/Details")
resp, err = client.Do(req)
if err != nil {
    fmt.Printf("Error : %s", err)
}

Now, the second http call is failing with a 401 access-denied error. A different REST client (a firefox plugin) correctly gets the details from the server, so I know that nothing is wrong on the server side. Do I need to pass some kind of session string or something that we got in the previous request ?

解决方案

Okay. I have resolved this. I just needed to create a cookie jar.

I am surprised that this is not handled by default by the golang http req/client class.

The code that I had to use was:

type myjar struct {
    jar map[string] []*http.Cookie
}

func (p* myjar) SetCookies(u *url.URL, cookies []*http.Cookie) {
    fmt.Printf("The URL is : %s\n", u.String())
    fmt.Printf("The cookie being set is : %s\n", cookies)
    p.jar [u.Host] = cookies
}

func (p *myjar) Cookies(u *url.URL) []*http.Cookie {
    fmt.Printf("The URL is : %s\n", u.String())
    fmt.Printf("Cookie being returned is : %s\n", p.jar[u.Host])
    return p.jar[u.Host]
}

and then in main:

    jar := &myjar{}
    jar.jar = make(map[string] []*http.Cookie)
    client.Jar = jar

Works.

这篇关于经过认证的来自golang的http客户端请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆