tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/duplex/mux/listen_io.go (about) 1 package mux 2 3 import ( 4 "io" 5 "net" 6 "os" 7 ) 8 9 // ioListener wraps a single ReadWriteCloser to use as a listener. 10 type ioListener struct { 11 io.ReadWriteCloser 12 } 13 14 // Accept will always return the wrapped ReadWriteCloser as a mux session. 15 func (l *ioListener) Accept() (Session, error) { 16 return New(l.ReadWriteCloser), nil 17 } 18 19 func (l *ioListener) Addr() net.Addr { 20 return nil 21 } 22 23 type ioduplex struct { 24 io.WriteCloser 25 io.ReadCloser 26 } 27 28 func (d *ioduplex) Close() error { 29 if err := d.WriteCloser.Close(); err != nil { 30 return err 31 } 32 if err := d.ReadCloser.Close(); err != nil { 33 return err 34 } 35 return nil 36 } 37 38 // ListenIO returns an IOListener that gives a mux session based on seperate 39 // WriteCloser and ReadClosers. 40 func ListenIO(out io.WriteCloser, in io.ReadCloser) (Listener, error) { 41 return &ioListener{ 42 &ioduplex{out, in}, 43 }, nil 44 } 45 46 // ListenStdio is a convenience for calling ListenIO with Stdout and Stdin. 47 func ListenStdio() (Listener, error) { 48 return ListenIO(os.Stdout, os.Stdin) 49 }