-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
stream.go
68 lines (63 loc) · 1.33 KB
/
stream.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
package playwright
import (
"bufio"
"encoding/base64"
"os"
"path/filepath"
)
type streamImpl struct {
channelOwner
}
func (s *streamImpl) SaveAs(path string) error {
err := os.MkdirAll(filepath.Dir(path), 0o777)
if err != nil {
return err
}
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for {
binary, err := s.channel.Send("read", map[string]interface{}{"size": 1024 * 1024})
if err != nil {
return err
}
bytes, err := base64.StdEncoding.DecodeString(binary.(string))
if err != nil {
return err
}
if len(bytes) == 0 {
break
}
_, err = writer.Write(bytes)
if err != nil {
return err
}
}
return writer.Flush()
}
func (s *streamImpl) ReadAll() ([]byte, error) {
var data []byte
for {
binary, err := s.channel.Send("read", map[string]interface{}{"size": 1024 * 1024})
if err != nil {
return nil, err
}
bytes, err := base64.StdEncoding.DecodeString(binary.(string))
if err != nil {
return nil, err
}
if len(bytes) == 0 {
break
}
data = append(data, bytes...)
}
return data, nil
}
func newStream(parent *channelOwner, objectType string, guid string, initializer map[string]interface{}) *streamImpl {
stream := &streamImpl{}
stream.createChannelOwner(stream, parent, objectType, guid, initializer)
return stream
}