Debian Codegraph @

lib/examples/compare-chromedp/cookie/main.go

raw
1 // Package main ...
2 package main
3
4 import (
5 "encoding/json"
6 "fmt"
7 "log"
8 "net"
9 "net/http"
10 "time"
11
12 "github.com/go-rod/rod"
13 "github.com/go-rod/rod/lib/proto"
14 )
15
16 // This example demonstrates how we can modify the cookies on a web page.
17 func main() {
18 expr := proto.TimeSinceEpoch(time.Now().Add(180 * 24 * time.Hour).Unix())
19
20 page := rod.New().MustConnect().MustPage()
21
22 page.MustSetCookies(&proto.NetworkCookieParam{
23 Name: "cookie1",
24 Value: "value1",
25 Domain: "127.0.0.1",
26 HTTPOnly: true,
27 Expires: expr,
28 }, &proto.NetworkCookieParam{
29 Name: "cookie2",
30 Value: "value2",
31 Domain: "127.0.0.1",
32 HTTPOnly: true,
33 Expires: expr,
34 })
35
36 page.MustNavigate(cookieServer())
37
38 // read network values
39 for i, cookie := range page.MustCookies() {
40 log.Printf("chrome cookie %d: %+v", i, cookie)
41 }
42
43 // chrome received cookies
44 log.Printf("chrome received cookies: %s", page.MustElement(`#result`).MustText())
45 }
46
47 // cookieServer creates a simple HTTP server that logs any passed cookies.
48 func cookieServer() string {
49 l, _ := net.Listen("tcp4", "127.0.0.1:0")
50 go func() {
51 _ = http.Serve(l, http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
52 cookies := req.Cookies()
53 for i, cookie := range cookies {
54 log.Printf("from %s, server received cookie %d: %v", req.RemoteAddr, i, cookie)
55 }
56 buf, err := json.MarshalIndent(req.Cookies(), "", " ")
57 if err != nil {
58 http.Error(res, err.Error(), http.StatusInternalServerError)
59 return
60 }
61 _, _ = fmt.Fprintf(res, indexHTML, string(buf))
62 }))
63 }()
64 return "http://" + l.Addr().String()
65 }
66
67 const (
68 indexHTML = `<!doctype html>
69 <html>
70 <body>
71 <div id="result">%s</div>
72 </body>
73 </html>`
74 )