Curl with cookies to Golang HTTP request


Curl with cookies to Golang HTTP request

我正试图从一个使用netscape HTTP cookie文件登录的旧网站获取信息。下面是我的curl请求:

// Do login request and get cookie
curl -c cookies -X POST -i -v https://foobar.com/login
// Use generated cookie file to get more data about the user
curl -b cookies -i -v https://foobar.com/data
在PHP中,你可以这样做:
// Do login request and get cookie
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://foobar/login');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, './cookies');
curl_setopt($ch, CURLOPT_COOKIEFILE, './cookies');  
$user = curl_exec($ch);
// Use generated cookie file to get data about the user 
curl_setopt($ch, CURLOPT_URL, 'https://foobar/login');
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, './cookies');
curl_setopt($ch, CURLOPT_COOKIEFILE, './cookies');  
$data = curl_exec($ch);

有一种方法来做到这一点使用std http包在Go?

保存cookie:

// do whatever is needed to login and get the cookie
response, err := http.PostForm("http://localhost:8080/login", url.Values{"username": {"foo"}, "password": {"bar"}})
if err != nil {
    log.Fatal(err)
}
var savedCookie *http.Cookie
for _, cookie := range response.Cookies() {
    if cookie.Name == "secret" {
        savedCookie = cookie
    }
}

一旦你有了cookie,你就可以构建另一个请求并添加cookie:

client := http.Client{}
request, err := http.NewRequest("GET", "http://localhost:8080/protected", nil)
if err != nil {
    log.Fatal(err)
}
request.AddCookie(savedCookie)
response, err := client.Do(request)
if err != nil {
    log.Fatal(err)
}

如果您有多个cookie,您可以使用CookieJar并直接在客户端设置它们:

client := &http.Client{
    Jar: jar,
}