golang create io.reader from string


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:

examples/create-io-reader/create_io_reader.go
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))
    }

}

examples/create-io-reader/create_io_reader.out
*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