forked from asticode/go-astilectron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
73 lines (63 loc) · 1.38 KB
/
reader.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
package astilectron
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"strings"
"github.com/asticode/go-astilog"
)
// reader represents an object capable of reading in the TCP server
type reader struct {
ctx context.Context
d *dispatcher
r io.ReadCloser
}
// newReader creates a new reader
func newReader(ctx context.Context, d *dispatcher, r io.ReadCloser) *reader {
return &reader{
ctx: ctx,
d: d,
r: r,
}
}
// close closes the reader properly
func (r *reader) close() error {
return r.r.Close()
}
// isEOFErr checks whether the error is an EOF error
// wsarecv is the error sent on Windows when the client closes its connection
func (r *reader) isEOFErr(err error) bool {
return err == io.EOF || strings.Contains(strings.ToLower(err.Error()), "wsarecv:")
}
// read reads from stdout
func (r *reader) read() {
var reader = bufio.NewReader(r.r)
for {
// Check context error
if r.ctx.Err() != nil {
return
}
// Read next line
var b []byte
var err error
if b, err = reader.ReadBytes('\n'); err != nil {
if !r.isEOFErr(err) {
astilog.Errorf("%s while reading", err)
continue
}
return
}
b = bytes.TrimSpace(b)
astilog.Debugf("Astilectron says: %s", b)
// Unmarshal
var e Event
if err = json.Unmarshal(b, &e); err != nil {
astilog.Errorf("%s while unmarshaling %s", err, b)
continue
}
// Dispatch
r.d.dispatch(e)
}
}