forked from Nilsen84/lunar-launcher-inject
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchrome_debugger.go
107 lines (88 loc) · 1.94 KB
/
chrome_debugger.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/avast/retry-go/v4"
"github.com/gorilla/websocket"
"github.com/phayes/freeport"
"io"
"net/http"
"os/exec"
"time"
)
type ChromeDebugger struct {
conn *websocket.Conn
}
func (d *ChromeDebugger) Close() error {
return d.conn.Close()
}
func (d *ChromeDebugger) Send(method string, params map[string]any) error {
return d.conn.WriteJSON(map[string]any{
"id": 1,
"method": method,
"params": params,
})
}
func StartProcessAndConnectDebugger(program string) (*ChromeDebugger, *exec.Cmd, error) {
port, err := freeport.GetFreePort()
if err != nil {
return nil, nil, err
}
cmd := exec.Command(program, fmt.Sprintf("--remote-debugging-port=%d", port))
if err = cmd.Start(); err != nil {
return nil, nil, err
}
d, err := ConnectDebugger(port)
if err != nil {
return nil, cmd, err
}
return d, cmd, nil
}
func ConnectDebugger(port int) (*ChromeDebugger, error) {
url, err := GetWebsocketDebuggerUrl(port)
if err != nil {
return nil, err
}
c, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return nil, err
}
return &ChromeDebugger{
conn: c,
}, nil
}
func GetWebsocketDebuggerUrl(port int) (string, error) {
var url string
err := retry.Do(
func() error {
r, err := http.Get(fmt.Sprintf("http://localhost:%d/json/list", port))
if err != nil {
return err
}
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
var targets []struct {
WebsocketUrl string `json:"webSocketDebuggerUrl"`
}
if err = json.Unmarshal(body, &targets); err != nil {
return err
} else if len(targets) == 0 {
return errors.New("no debugging targets found")
}
url = targets[0].WebsocketUrl
return nil
},
retry.Attempts(3),
retry.DelayType(retry.FixedDelay),
retry.Delay(350*time.Millisecond),
retry.LastErrorOnly(true),
)
if err != nil {
return "", err
}
return url, nil
}