"Tail -f"-like Generator in Go
This article discusses the creation of a "tail -f"-like generator in Go, which allows for real-time monitoring of a file's last lines. The initial Go implementation involved an asynchronous call with a goroutine continuously reading from the file. However, a more idiomatic approach is recommended using a wrapper around a reader that sleeps on EOF.
Improved Implementation:
The suggested improvement involves creating a tailReader struct that implements the io.ReadCloser interface. This reader sleeps when encountering an EOF, allowing for continuous monitoring without continuous polling.
<code class="go">type tailReader struct { io.ReadCloser } func (t tailReader) Read(b []byte) (int, error) { for { n, err := t.ReadCloser.Read(b) if n > 0 { return n, nil } else if err != io.EOF { return n, err } time.Sleep(10 * time.Millisecond) } }</code>
To create a tailReader, use newTailReader(fileName). This reader can be used with any provider that accepts an io.Reader, such as bufio.Scanner or json.NewDecoder.
Advantages:
This method offers several advantages over the goroutine approach:
The above is the detailed content of How to Build a \'tail -f\' Generator in Go with an Efficient Sleep-Based Approach?. For more information, please follow other related articles on the PHP Chinese website!