vendor/github.com/go-rod/rod/lib/proto/a_interface.go
71 lines · 1721 bytes
1// Package proto is a lib to encode/decode the data of the cdp protocol.
2package proto
3
4import (
5 "context"
6 "encoding/json"
7 "reflect"
8 "strings"
9)
10
11// Client interface to send the request.
12// So that this lib doesn't handle anything has side effect.
13type Client interface {
14 Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error)
15}
16
17// Sessionable type has a proto.TargetSessionID for its methods.
18type Sessionable interface {
19 GetSessionID() TargetSessionID
20}
21
22// Contextable type has a context.Context for its methods.
23type Contextable interface {
24 GetContext() context.Context
25}
26
27// Request represents a cdp.Request.Method.
28type Request interface {
29 // ProtoReq returns the cdp.Request.Method
30 ProtoReq() string
31}
32
33// Event represents a cdp.Event.Params.
34type Event interface {
35 // ProtoEvent returns the cdp.Event.Method
36 ProtoEvent() string
37}
38
39// GetType from method name of this package,
40// such as proto.GetType("Page.enable") will return the type of proto.PageEnable.
41func GetType(methodName string) reflect.Type {
42 return types[methodName]
43}
44
45// ParseMethodName to domain and name.
46func ParseMethodName(method string) (domain, name string) {
47 arr := strings.Split(method, ".")
48 return arr[0], arr[1]
49}
50
51// call method with request and response containers.
52func call(method string, req, res interface{}, c Client) error {
53 ctx := context.Background()
54 if cta, ok := c.(Contextable); ok {
55 ctx = cta.GetContext()
56 }
57
58 sessionID := ""
59 if tsa, ok := c.(Sessionable); ok {
60 sessionID = string(tsa.GetSessionID())
61 }
62
63 bin, err := c.Call(ctx, sessionID, method, req)
64 if err != nil {
65 return err
66 }
67 if res == nil {
68 return nil
69 }
70 return json.Unmarshal(bin, res)
71}