From bb84332ef7ca114f0c608bbea7f11451f010a831 Mon Sep 17 00:00:00 2001 From: xegineering Date: Wed, 27 Nov 2024 21:55:40 +0100 Subject: Handle read error after processing buffer This is recommended by the Go standard library. One reason is that a Reader might deliver the last couple of bytes together with the EOF error. This is only handled correctly if the returned bytes are processed first and the error is handled later. [1]: https://pkg.go.dev/io#Reader --- soundbox/streaming.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'soundbox') diff --git a/soundbox/streaming.go b/soundbox/streaming.go index 5852dcf..2686f47 100644 --- a/soundbox/streaming.go +++ b/soundbox/streaming.go @@ -29,19 +29,19 @@ func streamContext(ctx context.Context, r io.Reader, targets []net.HardwareAddr) for { buffer := make([]byte, bufferSize) - i, err := r.Read(buffer) - if err != nil { - if errors.Is(err, io.EOF) { - break - } else { - return err - } - } + i, readErr := r.Read(buffer) for _, conn := range conns { conn.SetDeadline(time.Now().Add(writeTimeout)) - _, err = conn.Write(buffer[:i]) - if err != nil { - return err + _, writeErr := conn.Write(buffer[:i]) + if writeErr != nil { + return writeErr + } + } + if readErr != nil { + if errors.Is(readErr, io.EOF) { + break + } else { + return readErr } } } -- cgit v1.2.3-70-g09d2