forked from playwright-community/playwright-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.go
95 lines (86 loc) · 2.21 KB
/
transport.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
package playwright
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"os"
"sync"
"gopkg.in/square/go-jose.v2/json"
)
type pipeTransport struct {
stdin io.WriteCloser
stdout io.ReadCloser
onmessage func(msg *message)
rLock sync.Mutex
}
func (t *pipeTransport) Start() error {
reader := bufio.NewReader(t.stdout)
for {
lengthContent := make([]byte, 4)
_, err := io.ReadFull(reader, lengthContent)
if err == io.EOF || errors.Is(err, os.ErrClosed) {
return nil
} else if err != nil {
return fmt.Errorf("could not read padding: %w", err)
}
length := binary.LittleEndian.Uint32(lengthContent)
msg := &message{}
if err := json.NewDecoder(io.LimitReader(reader, int64(length))).Decode(&msg); err != nil {
return fmt.Errorf("could not decode json: %w", err)
}
if os.Getenv("DEBUGP") != "" {
fmt.Print("RECV>")
if err := json.NewEncoder(os.Stderr).Encode(msg); err != nil {
log.Printf("could not encode json: %v", err)
}
}
t.onmessage(msg)
}
}
type errorPayload struct {
Name string `json:"name"`
Message string `json:"message"`
Stack string `json:"stack"`
}
type message struct {
ID int `json:"id"`
GUID string `json:"guid"`
Method string `json:"method"`
Params map[string]interface{} `json:"params"`
Result interface{} `json:"result"`
Error *struct {
Error errorPayload `json:"error"`
} `json:"error"`
}
func (t *pipeTransport) Send(message map[string]interface{}) error {
msg, err := json.Marshal(message)
if err != nil {
return fmt.Errorf("could not marshal json: %w", err)
}
if os.Getenv("DEBUGP") != "" {
fmt.Print("SEND>")
if err := json.NewEncoder(os.Stderr).Encode(message); err != nil {
log.Printf("could not encode json: %v", err)
}
}
lengthPadding := make([]byte, 4)
t.rLock.Lock()
defer t.rLock.Unlock()
binary.LittleEndian.PutUint32(lengthPadding, uint32(len(msg)))
if _, err = t.stdin.Write(lengthPadding); err != nil {
return err
}
if _, err = t.stdin.Write(msg); err != nil {
return err
}
return nil
}
func newPipeTransport(stdin io.WriteCloser, stdout io.ReadCloser) *pipeTransport {
return &pipeTransport{
stdout: stdout,
stdin: stdin,
}
}