Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Proposal to add ReaderFunc to package io
/*
https://play.golang.org/p/iWDGHj_-X_
This programs generates 32 random bytes formatted à la "hexdump -C".
It does it in just 2 lines of code using the power of the standard library
and a trick to convert a func Read([]byte) (int, error) into an io.Reader.
Inspiration: see HandlerFunc in net/http
Note: on the Go Playground the seed is NOT random.
Author: Olivier Mengué
https://github.com/dolmen-go/
*/
package main
import (
"encoding/hex"
"io"
"math/rand" // alternative: "crypto/rand"
"os"
)
// ReaderFunc allows to convert an io.Reader.Read-like function into an io.Reader
type ReaderFunc func([]byte) (n int, err error)
// Read implements the io.Reader interface
func (read ReaderFunc) Read(p []byte) (int, error) {
return read(p)
}
func main() {
// Transform func rand.Read into an io.Reader
randReader := ReaderFunc(rand.Read)
// Read 32 bytes from randReader and dump in hex
io.CopyN(hex.Dumper(os.Stdout), randReader, 32)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment