Home > database >  Does Go have a format specifier for io.Readers?
Does Go have a format specifier for io.Readers?

Time:02-08

What I want is something like this:

r := strings.NewReader("fee fi fo fum")
fmt.Printf("%r\n", r)

where the %r would be a format specifier that reads from an io.Reader. I didn't see anything like that in the fmt documentation https://pkg.go.dev/fmt, but it's possible I missed it.

CodePudding user response:

Does Go have a format specifier for io.Readers?

No.

CodePudding user response:

An io.Reader may be a stream which never ends, as such a fmt.Printf rendering may never complete.

If you know there will be a discrete payload and it's not excessively large, you can load the contents to memory:

r := strings.NewReader("fee fi fo fum")
b, _ := io.ReadAll(r)
fmt.Printf("%q\n", b)

https://go.dev/play/p/DZybA_f6Ole

This will however move the reader current position to the end, so if you need to "replay" the reader to a future call, you need to use another io.Reader (e.g. bytes Buffer) to hold the original content e.g.

r := strings.NewReader("fee fi fo fum")

if debug {
    var b bytes.Buffer
    _, err = io.Copy(&b, r) // handle err

    log.Printf("io.Reader content: %q\n", b.String())

    r = &b // replay
}

// r io.Reader content and position perserved

https://go.dev/play/p/JRS34uX1R1G

  •  Tags:  
  • Related