1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
package utils
import (
"bufio"
"context"
)
type readStringResult = struct {
str string
err error
}
// ReadStringContext calls bufio.Reader.ReadString() but uses a context. Note that if the
// ctx.Done() fires, the ReadString() call is still active, and bufio is not re-entrant, so it is
// important for callers to error out of further use of the bufio. Also, the goroutine will not
// exit until the bufio's underlying connection is closed.
func ReadStringContext(ctx context.Context, reader *bufio.Reader, delim byte) (string, error) {
result := make(chan *readStringResult, 1)
go func() {
str, err := reader.ReadString(delim)
result <- &readStringResult{
str: str,
err: err,
}
}()
select {
case res := <-result:
return res.str, res.err
case <-ctx.Done():
return "", ctx.Err()
}
}
|