| 1 |
// Package main ... |
| 2 |
package main |
| 3 |
|
| 4 |
import ( |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
"log" |
| 8 |
"net" |
| 9 |
"net/http" |
| 10 |
|
| 11 |
"github.com/go-rod/rod" |
| 12 |
) |
| 13 |
|
| 14 |
// This example demonstrates how to set a HTTP header on requests. |
| 15 |
func main() { |
| 16 |
host := headerServer() |
| 17 |
|
| 18 |
page := rod.New().MustConnect().MustPage(host) |
| 19 |
|
| 20 |
page.MustSetExtraHeaders("X-Header", "my request header") |
| 21 |
page.MustNavigate(host) |
| 22 |
res := page.MustElement("#result").MustText() |
| 23 |
|
| 24 |
log.Printf("received headers: %s", res) |
| 25 |
} |
| 26 |
|
| 27 |
// headerServer is a simple HTTP server that displays the passed headers in the html. |
| 28 |
func headerServer() string { |
| 29 |
l, _ := net.Listen("tcp4", "127.0.0.1:0") |
| 30 |
go func() { |
| 31 |
_ = http.Serve(l, http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { |
| 32 |
buf, err := json.MarshalIndent(req.Header, "", " ") |
| 33 |
if err != nil { |
| 34 |
http.Error(res, err.Error(), http.StatusInternalServerError) |
| 35 |
return |
| 36 |
} |
| 37 |
_, _ = fmt.Fprintf(res, indexHTML, string(buf)) |
| 38 |
})) |
| 39 |
}() |
| 40 |
return "http://" + l.Addr().String() |
| 41 |
} |
| 42 |
|
| 43 |
const indexHTML = `<!doctype html> |
| 44 |
<html> |
| 45 |
<body> |
| 46 |
<div id="result">%s</div> |
| 47 |
</body> |
| 48 |
</html>` |