-
Notifications
You must be signed in to change notification settings - Fork 45
/
example_logging_test.go
66 lines (57 loc) · 1.57 KB
/
example_logging_test.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
package cdp_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"github.com/mafredri/cdp"
"github.com/mafredri/cdp/rpcc"
)
// LogCodec captures the output from writing RPC requests and reading
// responses on the connection. It implements rpcc.Codec via
// WriteRequest and ReadResponse.
type LogCodec struct{ conn io.ReadWriter }
// WriteRequest marshals v into a buffer, writes its contents onto the
// connection and logs it.
func (c *LogCodec) WriteRequest(req *rpcc.Request) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(req); err != nil {
return err
}
fmt.Printf("SEND: %s", buf.Bytes())
_, err := c.conn.Write(buf.Bytes())
if err != nil {
return err
}
return nil
}
// ReadResponse unmarshals from the connection into v whilst echoing
// what is read into a buffer for logging.
func (c *LogCodec) ReadResponse(resp *rpcc.Response) error {
var buf bytes.Buffer
if err := json.NewDecoder(io.TeeReader(c.conn, &buf)).Decode(resp); err != nil {
return err
}
fmt.Printf("RECV: %s\n", buf.String())
return nil
}
func Example_logging() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
newLogCodec := func(conn io.ReadWriter) rpcc.Codec {
return &LogCodec{conn: conn}
}
conn, err := rpcc.Dial("ws://"+TestSockSrv+"/example_logging", rpcc.WithCodec(newLogCodec))
if err != nil {
fmt.Println(err)
}
defer conn.Close()
c := cdp.NewClient(conn)
if err = c.Network.Enable(ctx, nil); err != nil {
fmt.Println(err)
}
// Output:
// SEND: {"id":1,"method":"Network.enable"}
// RECV: {"id":1,"result":{}}
}