github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/utils/binary/network.go (about) 1 package binary 2 3 // from https://github.com/Mrs4s/MiraiGo/blob/master/binary/reader.go 4 5 import ( 6 "encoding/binary" 7 "io" 8 "net" 9 ) 10 11 type NetworkReader struct { 12 conn net.Conn 13 } 14 15 func NewNetworkReader(conn net.Conn) *NetworkReader { 16 return &NetworkReader{conn: conn} 17 } 18 19 func (r *NetworkReader) ReadByte() (byte, error) { 20 buf := make([]byte, 1) 21 n, err := r.conn.Read(buf) 22 if err != nil { 23 return 0, err 24 } 25 if n != 1 { 26 return r.ReadByte() 27 } 28 return buf[0], nil 29 } 30 31 func (r *NetworkReader) ReadBytes(len int) ([]byte, error) { 32 buf := make([]byte, len) 33 _, err := io.ReadFull(r.conn, buf) 34 return buf, err 35 } 36 37 func (r *NetworkReader) ReadInt32() (int32, error) { 38 b := make([]byte, 4) 39 _, err := r.conn.Read(b) 40 if err != nil { 41 return 0, err 42 } 43 return int32(binary.BigEndian.Uint32(b)), nil 44 }