In Go, you can use the Peek()
method of a bufio.Reader
to check if there is any data left to read without consuming it.
Here's an example:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Create a new Reader from stdin
reader := bufio.NewReader(os.Stdin)
// Read a line of input
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input:", err)
return
}
// Check if there is any remaining data
remaining := reader.Buffered() > 0
fmt.Println("Remaining data:", remaining)
// Print the line
fmt.Println("Read line:", line)
}
In this example, reader.Buffered()
returns the number of bytes that can be read from the internal buffer without making additional I/O calls. By checking if this value is greater than 0, you can determine if there is any data left to read.
Note that Peek()
method also returns the next n bytes without advancing the reader, so you can use it instead of Buffered()
if you need to check the actual content of the remaining data.