-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathmain.go
73 lines (63 loc) · 1.65 KB
/
main.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Command headers is a chromedp example demonstrating how to add extra HTTP
// headers to browser requests.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
func main() {
port := flag.Int("port", 8544, "port")
flag.Parse()
// run server
go headerServer(fmt.Sprintf(":%d", *port))
// create context
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// run task list
var res string
err := chromedp.Run(ctx, setheaders(
fmt.Sprintf("http://localhost:%d", *port),
map[string]interface{}{
"X-Header": "my request header",
},
&res,
))
if err != nil {
log.Fatal(err)
}
log.Printf("received headers: %s", res)
}
// headerServer is a simple HTTP server that displays the passed headers in the html.
func headerServer(addr string) error {
mux := http.NewServeMux()
mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
buf, err := json.MarshalIndent(req.Header, "", " ")
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(res, indexHTML, string(buf))
})
return http.ListenAndServe(addr, mux)
}
// setheaders returns a task list that sets the passed headers.
func setheaders(host string, headers map[string]interface{}, res *string) chromedp.Tasks {
return chromedp.Tasks{
network.Enable(),
network.SetExtraHTTPHeaders(network.Headers(headers)),
chromedp.Navigate(host),
chromedp.Text(`#result`, res, chromedp.ByID, chromedp.NodeVisible),
}
}
const indexHTML = `<!doctype html>
<html>
<body>
<div id="result">%s</div>
</body>
</html>`