Created
April 14, 2017 16:16
-
-
Save dolmen/f60fcb6bda23f3b24e69d6dd4cef3c8e to your computer and use it in GitHub Desktop.
Proposal to add ReaderFunc to package io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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