Golang : Read from buffered reader until specific number of bytes
Problem :
You have a buffered reader streaming in with data. You want to limit each read to a specific size for processing purpose before advancing to the next read.
Solution :
Specify the size of the buffer (p) to the limit you want per read. Use io.ReadFull to consume data from the buffered reader and fill up to the buffer (p in the code example below) max size.
package main
import (
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader("Profession.socketloop.com says Hello World!")
// the read is limited by the size of p
p := make([]byte, 32)
fmt.Printf("Read until %d bytes and advance the reader\n", len(p))
n, err := io.ReadFull(reader, p) // read all bytes into buffer
// NOTE : this is just a simple tutorial to demonstrate how to limit your read to certain
// size. You might want to turn this into a loop
// to read the buffered reader until EOF
fmt.Printf("\n%s ", p)
fmt.Printf("\n Number of bytes copied : %d with error : %v\n", n, err)
}
Output :
Read until 32 bytes and advance the reader
Profession.socketloop.com says H
Number of bytes copied : 32 with error :
NOTE : this is just a simple tutorial to demonstrate how to limit your read to certain size with a fixed size strings buffered reader. You might want to turn this into a loop to continuously read the buffered reader stream data until EOF.
Reference :
See also : Golang : Read a file line by line
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+10.8k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+22k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+5.7k Golang : Reverse by word
+7.2k Golang : Ackermann function example
+13.5k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+4.1k Python : Convert(cast) bytes to string example
+3.8k Golang : Customize scanner.Scanner to treat dash as part of identifier
+23.2k Golang : convert rune to integer value
+16.7k Golang : Check if a directory exist or not
+11.9k Golang : Date and Time formatting
+25.8k Golang : Record voice(audio) from microphone to .WAV file