string to io.ReadCloser
时间:2019-12-09 05:17:05 +0800 CST 浏览:3364

字符串转io.ReadCloser方法

package main    
import (    
    "bytes"    
    "fmt"    
    "io/ioutil"    
)    
func main() {    
    r := ioutil.NopCloser(bytes.NewReader([]byte("hello world"))) // r type is io.ReadCloser    
    // example to test r    
    buf := new(bytes.Buffer)    
    buf.ReadFrom(r)    
    r.Close()    
    s := buf.String()    
    fmt.Println(s)    
}

为了避免字符串到[]byte的转换,最好使用strings.NewReader()

package main

import (
    "bytes"
        "strings"
    "fmt"
    "io/ioutil"
)

func main() {
    r := ioutil.NopCloser(strings.NewReader("hello world")) // r type is io.ReadCloser

    // example to test r
    buf := new(bytes.Buffer)
    buf.ReadFrom(r)
    r.Close()
    s := buf.String()
    fmt.Println(s)
}


如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。

本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。


来说两句吧