/
stdio.go
82 lines (63 loc) · 1.7 KB
/
stdio.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
package connection
import (
"fmt"
"io"
"net"
"os"
"time"
)
type Stdio struct {
in io.ReadCloser
out io.WriteCloser
}
func NewDefaultStdio() *Stdio {
return NewStdio(os.Stdin, os.Stdout)
}
func NewStdio(in io.ReadCloser, out io.WriteCloser) *Stdio {
return &Stdio{
in: in,
out: out,
}
}
// Read implements io.Reader interface.
func (s *Stdio) Read(b []byte) (int, error) {
n, err := s.in.Read(b)
if err != nil {
return 0, fmt.Errorf("Error reading from stdio: %w", err)
}
return n, nil
}
// Write implements io.Writer interface.
func (s *Stdio) Write(b []byte) (int, error) {
n, err := s.out.Write(b)
if err != nil {
return 0, fmt.Errorf("Error writing to stdio: %w", err)
}
return n, nil
}
// Close implements io.Closer interface.
func (s *Stdio) Close() error {
errIn := s.in.Close()
errOut := s.out.Close()
if errIn != nil {
return fmt.Errorf("Error closing stdio stdin: %w", errIn)
}
if errOut != nil {
return fmt.Errorf("Errors closing stdio stdout: %w", errOut)
}
return nil
}
// LocalAddr implements net.Conn interface.
func (s Stdio) LocalAddr() net.Addr { return s }
// RemoteAddr implements net.Conn interface.
func (s Stdio) RemoteAddr() net.Addr { return s }
// SetDeadline implements net.Conn interface.
func (Stdio) SetDeadline(t time.Time) error { return nil }
// SetReadDeadline implements net.Conn interface.
func (Stdio) SetReadDeadline(t time.Time) error { return nil }
// SetWriteDeadline implements net.Conn interface.
func (Stdio) SetWriteDeadline(t time.Time) error { return nil }
// Network implements net.Addr interface.
func (Stdio) Network() string { return "Stdio" }
// String implements net.Addr interface.
func (Stdio) String() string { return "Stdio" }