Last active
August 20, 2018 14:21
-
-
Save mafredri/2f413e7bd1fe6e7d5afd2318f2a01549 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
"github.com/mafredri/cdp" | |
"github.com/mafredri/cdp/devtool" | |
"github.com/mafredri/cdp/protocol/network" | |
"github.com/mafredri/cdp/protocol/page" | |
"github.com/mafredri/cdp/rpcc" | |
) | |
func main() { | |
err := run(5 * time.Second) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func run(timeout time.Duration) error { | |
go func() { | |
srv := http.Server{ | |
Addr: "localhost:8080", | |
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Println(r.Header) | |
w.WriteHeader(200) | |
fmt.Fprintln(w, "Hello!") | |
}), | |
} | |
log.Fatal(srv.ListenAndServe()) | |
}() | |
ctx, cancel := context.WithTimeout(context.Background(), timeout) | |
defer cancel() | |
devt := devtool.New("http://127.0.0.1:9222") | |
pt, err := devt.Get(ctx, devtool.Page) | |
if err != nil { | |
pt, err = devt.Create(ctx) | |
if err != nil { | |
return err | |
} | |
} | |
conn, err := rpcc.DialContext(ctx, pt.WebSocketDebuggerURL) | |
if err != nil { | |
return err | |
} | |
defer conn.Close() | |
c := cdp.NewClient(conn) | |
domContent, err := c.Page.DOMContentEventFired(ctx) | |
if err != nil { | |
return err | |
} | |
defer domContent.Close() | |
if err = c.Page.Enable(ctx); err != nil { | |
return err | |
} | |
c.Network.Enable(ctx, nil) | |
err = c.Network.SetExtraHTTPHeaders(ctx, | |
network.NewSetExtraHTTPHeadersArgs( | |
[]byte(`{"Accept-Language": "en_US", "Boop": "Beep"}`), | |
), | |
) | |
if err != nil { | |
return err | |
} | |
navArgs := page.NewNavigateArgs("http://localhost:8080") | |
nav, err := c.Page.Navigate(ctx, navArgs) | |
if err != nil { | |
return err | |
} | |
if _, err = domContent.Recv(); err != nil { | |
return err | |
} | |
fmt.Printf("Page loaded with frame ID: %s\n", nav.FrameID) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment