dpq59734
2012-12-07 15:12
浏览 238
已采纳

从Go中的Writer获取字符串的最佳方法

I have a piece of code that returns a web page using the built-in template system. It accepts a ResponseWriter to which the resulting markup is written. I now want to get to the markup as a string and put it in a database in some cases. I factored out a method that accepts a normal Writer instead of a ResponseWriter and am now trying to get to the written content. Aha - a Pipe may be what I need and then I can get the string with ReadString from the bufio library. But it turns out that the PipeReader coming out from the pipe is not compatible with Reader (that I would need for the ReadString method). W00t. Big surprise. So I could just read into byte[]s using the PipeReader but it feels a bit wrong when ReadString is there.

So what would be the best way to do it? Should I stick with the Pipe and read bytes or is there something better that I haven't found in the manual?

图片转代码服务由CSDN问答提供 功能建议

我有一段代码可以使用内置模板系统返回网页。 它接受将结果标记写入其中的 ResponseWriter 。 现在,我想将标记作为字符串并将其放入数据库中(在某些情况下)。 我提出了一个接受常规 Writer 而不是 ResponseWriter 的方法,现在尝试获取书面内容。 啊哈- Pipe 可能是我所需要的,然后我可以从 bufio 库中使用 ReadString 获得字符串。 但是事实证明,从管道中出来的 PipeReader Reader 不兼容(我需要 ReadString 方法)。 W00t。 大惊喜。 因此,我可以使用 PipeReader 读入byte [] s,但是当 ReadString 存在时,感觉有点不对。

那么最好的方法是什么? 我应该坚持使用 Pipe 并读取字节还是在手册中找不到更好的东西?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqian9729 2012-12-07 15:29
    已采纳

    If your function accepts an io.Writer, you can pass a *bytes.Buffer to capture the output.

    // import "bytes"
    buf := new(bytes.Buffer)
    f(buf)
    buf.String() // returns a string of what was written to it
    

    If it requires an http.ResponseWriter, you can use a *httptest.ResponseRecorder. A response recorder holds all information that can be sent to a ResponseWriter, but the body is just a *bytes.Buffer.

    // import "net/http/httptest"
    r := httptest.NewRecorder()
    f(r)
    r.Body.String() // r.Body is a *bytes.Buffer
    
    点赞 评论
  • dswe30290 2016-06-29 08:59

    The below code is possibly the simplest way to convert Writer (or any type) to string

    package main
    
    import "fmt"
    import "io"
    import "reflect"
    
    func main(){
        var temp io.Writer
        output := fmt.Sprint(temp)
        fmt.Println(reflect.TypeOf(output))
    
    }
    

    Output:

    string
    
    点赞 评论

相关推荐 更多相似问题