forked from rancher/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
94 lines (79 loc) · 1.86 KB
/
io.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
package proxy
import (
"encoding/json"
"io"
"github.com/Sirupsen/logrus"
"github.com/rancher/websocket-proxy/common"
)
type HTTPWriter struct {
headerWritten bool
Message common.HTTPMessage
MessageKey string
Chan chan<- common.Message
}
func (h *HTTPWriter) Write(bytes []byte) (n int, err error) {
h.Message.Body = bytes
if err := h.writeMessage(); err != nil {
return 0, err
}
return len(bytes), nil
}
func (h *HTTPWriter) writeMessage() error {
bytes, err := json.Marshal(&h.Message)
if err != nil {
return err
}
m := common.Message{
Key: h.MessageKey,
Type: common.Body,
Body: string(bytes),
}
logrus.Debugf("HTTP WRITER %s: %#v", h.MessageKey, m)
h.Chan <- m
h.Message = common.HTTPMessage{}
return nil
}
func (h *HTTPWriter) Close() error {
h.Message.EOF = true
return h.writeMessage()
}
type HTTPReader struct {
Buffered []byte
Chan <-chan string
EOF bool
MessageKey string
}
func (h *HTTPReader) Close() error {
logrus.Debugf("HTTP READER CLOSE %s", h.MessageKey)
return nil
}
func (h *HTTPReader) Read(bytes []byte) (int, error) {
if len(h.Buffered) == 0 && !h.EOF {
if err := h.read(); err != nil {
return 0, err
}
}
count := copy(bytes, h.Buffered)
h.Buffered = h.Buffered[count:]
if h.EOF {
logrus.Debugf("HTTP READER RETURN EOF %s", h.MessageKey)
return count, io.EOF
}
logrus.Debugf("HTTP READER RETURN COUNT %s %d %d: %s", h.MessageKey, count, len(h.Buffered), bytes[:count])
return count, nil
}
func (h *HTTPReader) read() error {
str, ok := <-h.Chan
if !ok {
logrus.Debugf("HTTP READER CHANNEL EOF %s", h.MessageKey)
return io.EOF
}
var message common.HTTPMessage
if err := json.Unmarshal([]byte(str), &message); err != nil {
return err
}
logrus.Debugf("HTTP READER MESSAGE %s %s", h.MessageKey, message.Body)
h.Buffered = message.Body
h.EOF = message.EOF
return nil
}