Example: How to use ReadAtLeast from IO Package in Golang?
ReadAtLeast reads from r into buf until it has read at least min bytes. It returns specific errors to signal specific cases when the minimum couldn’t be read due to EOF.
Example
package main
import (
"io"
"fmt"
"strings"
)
type Example struct {
ReaderLength int
Minimum int
TextStr string
}
func main() {
examples := []Example{
{10, 5, "Go is a programming language created at Google in 2007."},
{10, 10, "Golang"},
{10, 00, "Robert Griesemer"},
{10, 15, "Jobs, Code, Videos and News for Go hackers."},
}
for _, ex := range examples {
rd := strings.NewReader(ex.TextStr)
buffer := make([]byte, ex.ReaderLength)
bytesRead, err := io.ReadAtLeast(rd, buffer, ex.Minimum)
fmt.Printf("\nLen(buffer)=%d, Min=%d, BytesRead=%d, Error=%v, (%s)\n",ex.ReaderLength, ex.Minimum, bytesRead, err, ex.TextStr)
}
}
Output
Len(buffer)=10, Min=5, BytesRead=10, Error=, (Go is a programming language created at Google in 2007.)
Len(buffer)=10, Min=10, BytesRead=6, Error=unexpected EOF, (Golang)
Len(buffer)=10, Min=0, BytesRead=0, Error=, (Robert Griesemer)
Len(buffer)=10, Min=15, BytesRead=0, Error=short buffer, (Jobs, Code, Videos and News for Go hackers.)
Most Helpful This Week
The return values of a function can be named in Golang
Print index and element or data from Array, Slice and Map
How to include and execute HTML template?
How to verify a string only contains letters, numbers, underscores, and dashes in Golang?
How to check if a string contains only letters in Golang?
Golang HTML parser