Use CancelReader to interrupt blocking reads
mainThe cancelreader package provides a way to interrupt blocking Read calls on an input reader.
To use it, wrap your reader with NewReader(reader). This returns a Reader instance that includes a Cancel() method.
Behavioral Notes:
- Files: If the input reader is an
*os.File, callingCancel()will successfully interrupt a blockingReadcall. TheReadcall will then return an error that can be checked usingerrors.Is(err, cancelreader.ErrCanceled). - Non-Files: If the input reader is not a
File, theCancel()method does nothing and always returnsfalse. - Windows Limitation: On Windows, cancellation currently only supports
os.Stdin(viaWaitForMultipleObjectwith overlapping reads fromCONIN$).
r, err := cancelreader.NewReader(file)
if err != nil {
// handle error
...
}
// cancel after five seconds
go func() {
time.Sleep(5 * time.Second)
r.Cancel()
}()
// keep reading
for {
var buf [1024]byte
_, err := r.Read(buf[:])
if errors.Is(err, cancelreader.ErrCanceled) {
fmt.Println("canceled!")
break
}
if err != nil {
// handle other errors
...
}
// handle data
...
}