-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstream.go
More file actions
58 lines (45 loc) · 1.2 KB
/
Copy pathstream.go
File metadata and controls
58 lines (45 loc) · 1.2 KB
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
package jsonrpc2
import (
"encoding/json"
"fmt"
"io"
)
// Stream encodes and decodes JSON messages.
// Each Read/Write call exchanges one complete JSON value.
// Errors are fatal and cause [Conn] to close.
type Stream interface {
// Read decodes one JSON value into v.
Read(v any) error
// Write encodes and sends one JSON value.
Write(obj any) error
// Close closes the underlying transport.
Close() error
}
type encoderStream struct {
stream io.ReadWriteCloser
decoder *json.Decoder
encoder *json.Encoder
}
var _ Stream = (*encoderStream)(nil)
// NewStream creates a [Stream] over stream for newline-delimited JSON.
func NewStream(stream io.ReadWriteCloser) Stream {
return &encoderStream{stream, json.NewDecoder(stream), json.NewEncoder(stream)}
}
func (s *encoderStream) Read(v any) error {
if err := s.decoder.Decode(v); err != nil {
return fmt.Errorf("decoding object: %w", err)
}
return nil
}
func (s *encoderStream) Write(v any) error {
if err := s.encoder.Encode(v); err != nil {
return fmt.Errorf("encoding object: %w", err)
}
return nil
}
func (s *encoderStream) Close() error {
if err := s.stream.Close(); err != nil {
return fmt.Errorf("closing: %w", err)
}
return nil
}