dongnaopa6200 2012-07-06 11:35
浏览 270
已采纳

来自golang的经过身份验证的http客户端请求

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 ?

  • 写回答

3条回答 默认 最新

  • douxiexie3574 2012-07-06 13:55
    关注

    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
    ", u.String())
        fmt.Printf("The cookie being set is : %s
    ", cookies)
        p.jar [u.Host] = cookies
    }
    
    func (p *myjar) Cookies(u *url.URL) []*http.Cookie {
        fmt.Printf("The URL is : %s
    ", u.String())
        fmt.Printf("Cookie being returned is : %s
    ", 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler