1. io.Reader转化为字符串, byte切片
import "bytes"
func StreamToByte(stream io.Reader) []byte {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.Bytes()
}
func StreamToString(stream io.Reader) string {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.String()
}
示例:
1) byte切片转io.Reader
package main
import (
"bytes"
"log"
)
func main() {
data := []byte("this is some data stored as a byte slice in Go Lang!")
// convert byte slice to io.Reader
reader := bytes.NewReader(data)
// read only 4 byte from our io.Reader
buf := make([]byte, 4)
n, err := reader.Read(buf)
if err != nil {
log.Fatal(err)
}
log.Println(string(buf[:n]))
}
2) io.Reader转byte切片
package main
import (
"bytes"
"log"
"strings"
)
func main() {
ioReaderData := strings.NewReader("this is some data stored as a byte slice in Go Lang!")
// creates a bytes.Buffer and read from io.Reader
buf := &bytes.Buffer{}
buf.ReadFrom(ioReaderData)
// retrieve a byte slice from bytes.Buffer
data := buf.Bytes()
// only read the first 4 bytes
log.Println(string(data[:4]))
}