如何在Golang中创建一个Curl Store Cookie?

时间:2017-05-17 17:42:14

标签: curl cookies go

我想发送一个发布/获取请求,并可以将Cookie存储在Program附近的文件中。

示例Php代码:

$___path="";
function send($url,$fields=array(),$reffer=false,$get=false)
{
    global $___path;
    $cookie_file_path = $___path."cookie.txt";//this file of cookies.
    $agent            = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1";
    $ch = curl_init(); 
    $headers[] = "Accept: */*";
    $headers[] = "Connection: Keep-Alive";
    curl_setopt($ch, CURLOPT_HTTPHEADER,  $headers);
    curl_setopt($ch, CURLOPT_HEADER,  0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);         
    if($reffer == false){}
    else
    {
        curl_setopt($ch,CURLOPT_REFERER,$reffer);
    }
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 
    curl_setopt($ch, CURLOPT_URL, $url);
    if($get)
    {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
    }
    else
    {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        if(count($fields) >= 1)
        {
            $POSTFIELDS = http_build_query($fields);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
        }
    }
    $result = curl_exec($ch); 
    return $result;
}

可以帮助我使用cookie jar商店吗?

这没有样本:https://github.com/juju/persistent-cookiejar

是否有人可以撰写关于https://golang.org/pkg/net/http/#CookieJar的样本?

1 个答案:

答案 0 :(得分:2)

您无需将Cookie保存到文件中,只需保持go进程正常运行即可。如果你真的想,你会做类似的事情:

import "net/http/cookiejar"
import "net/http"
import "encoding/json"
import "io/ioutil"

cookies := make(map[string][]*http.Cookie)
jar, _ := cookiejar.New(nil)
client := http.Client{Jar: jar}
r, _ := client.Get(/* do whatever */)
siteCookies := jar.Cookies(r.Request.URL)
cookies[r.Request.URL.String()] = siteCookies
data, _ := json.Marshal(cookies)
ioutil.WriteFile("/path/to/cookies.txt", data, 0644)

然后当你开始时,你会为每个键呼叫url.Parse读取该文件,然后用它来呼叫jar.SetCookies

https://play.golang.org/p/gQ_n6rPsdl