Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

golang create io.reader from string

  • NewReader
  • Read
  • EOF

Many tools in Golang expect an io.reader object as an input parameter What happens if you have a string and you'd like to pass that to such a function? You need to create an io.reader object that can read from that string:

package main

import (
	"fmt"
	"io"
	"strings"
)

func main() {
	someString := "hello world\nand hello go and more"
	myReader := strings.NewReader(someString)

	fmt.Printf("%T", myReader) // *strings.Reader

	buffer := make([]byte, 10)
	for {
		count, err := myReader.Read(buffer)
		if err != nil {
			if err != io.EOF {
				fmt.Println(err)
			}
			break
		}
		fmt.Printf("Count: %v\n", count)
		fmt.Printf("Data: %v\n", string(buffer))
	}

}
*strings.ReaderCount: 10
Data: hello worl
Count: 10
Data: d
and hell
Count: 10
Data: o go and m
Count: 3
Data: oreo and m