diff options
author | xegineering <me@xegineering.eu> | 2024-11-27 21:55:40 +0100 |
---|---|---|
committer | xegineering <me@xegineering.eu> | 2024-11-27 21:55:40 +0100 |
commit | bb84332ef7ca114f0c608bbea7f11451f010a831 (patch) | |
tree | 422f69f77e628573aec6e6291b6939a26ad238e8 | |
parent | 6b7da29eea100b92659a3f1f5df6958ebad544c8 (diff) | |
download | soundbox-go-bb84332ef7ca114f0c608bbea7f11451f010a831.tar soundbox-go-bb84332ef7ca114f0c608bbea7f11451f010a831.tar.zst soundbox-go-bb84332ef7ca114f0c608bbea7f11451f010a831.zip |
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
-rw-r--r-- | soundbox/streaming.go | 22 |
1 files changed, 11 insertions, 11 deletions
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 } } } |