github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/pipes/net/net.go (about) 1 package net 2 3 import ( 4 "context" 5 "net" 6 "os" 7 "sync" 8 9 "github.com/lmorg/murex/utils" 10 ) 11 12 // Net Io interface 13 type Net struct { 14 mutex sync.Mutex 15 ctx context.Context 16 forceClose func() 17 bRead uint64 18 bWritten uint64 19 dependents int 20 conn net.Conn 21 dataType string 22 protocol string 23 } 24 25 // DefaultDataType is unavailable for net Io interfaces 26 func (n *Net) DefaultDataType(bool) {} 27 28 // IsTTY always returns false because net Io interfaces are not a pseudo-TTY 29 func (n *Net) IsTTY() bool { return false } 30 31 func (n *Net) File() *os.File { 32 return nil 33 } 34 35 // SetDataType assigns a data type to the stream.Io interface 36 func (n *Net) SetDataType(dt string) { 37 n.mutex.Lock() 38 defer n.mutex.Unlock() 39 40 n.dataType = dt 41 } 42 43 // GetDataType read the stream.Io interface's data type 44 func (n *Net) GetDataType() string { 45 n.mutex.Lock() 46 defer n.mutex.Unlock() 47 48 return n.dataType 49 } 50 51 // Stats returns the bytes written and bytes read to the net Io interface 52 func (n *Net) Stats() (bytesWritten, bytesRead uint64) { 53 n.mutex.Lock() 54 bytesWritten = n.bWritten 55 bytesRead = n.bRead 56 n.mutex.Unlock() 57 return 58 } 59 60 // Open net Io interface 61 func (n *Net) Open() { 62 n.mutex.Lock() 63 defer n.mutex.Unlock() 64 65 n.dependents++ 66 } 67 68 // Close net Io interface 69 func (n *Net) Close() { 70 n.mutex.Lock() 71 defer n.mutex.Unlock() 72 73 n.dependents-- 74 75 if n.dependents == 0 { 76 err := n.conn.Close() 77 if err != nil { 78 os.Stderr.WriteString(err.Error() + utils.NewLineString) 79 } 80 } 81 82 if n.dependents < 0 { 83 panic("more closed dependants than open") 84 } 85 } 86 87 // ForceClose forces the net Io interface to close. This should only be called on reader interfaces 88 func (n *Net) ForceClose() { 89 n.forceClose() 90 }