/
cookies.go
48 lines (45 loc) · 1.08 KB
/
cookies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package lib
import (
"context"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"github.com/sirupsen/logrus"
"net/http"
"net/url"
"time"
)
func HttpCookies(rawCookies string) []*http.Cookie {
header := http.Header{}
header.Add("Cookie", rawCookies)
request := http.Request{Header: header}
return request.Cookies()
}
func CookieAction(link, rawCookies string, expire int) chromedp.ActionFunc {
rs, _ := url.Parse(link)
domain := rs.Hostname()
logrus.Println(domain)
return func(ctx context.Context) (err error) {
// create cookie expiration
var duration time.Duration
if expire == 0 {
duration = time.Duration(360 * 24)
} else {
duration = time.Duration(expire)
}
expr := cdp.TimeSinceEpoch(time.Now().Add(duration * time.Hour))
// add cookies to chrome
cookies := HttpCookies(rawCookies)
for _, item := range cookies {
// 设置cookies
err := network.SetCookie(item.Name, item.Value).
WithExpires(&expr).
WithDomain(domain).
Do(ctx)
if err != nil {
return err
}
}
return nil
}
}