dps123456789 2015-04-18 01:31
浏览 10
已采纳

在Go中用读者包裹作家吗?

I'm trying to write a function in Go which generates XML and returns a reader for it. However, the XML encoder seems to take a writer to write to and I'm not quite sure how to pipe the output of the writer to the reader I want to return.

I tried this:

func (i *Item) ToRss() io.Reader {                                                     
  reader, writer := io.Pipe()                                                             
  enc := xml.NewEncoder(writer)                                                           
  enc.Indent("  ", "   ")                                                                 
  enc.Encode(i)                                                                           
  return reader                                                                           
}

But when I run the following I get a fatal error:

  r := a.ToRss()
  buf := new(bytes.Buffer)
  buf.ReadFrom(r)
  s := buf.String()
  fmt.Println(s)

fatal error: all goroutines are asleep - deadlock!

Eventually I'd like to pipe the reader to the output of an HTTP request. Should I just return a []byte? Or is there a nice way to buffer the output so the client can use the reader?

Thanks!

  • 写回答

1条回答 默认 最新

  • dousheyan0375 2015-04-18 01:52
    关注

    A pipe does no internal buffering. It blocks on read or write until a corresponding write or read is called.

    You should use a bytes.Buffer inside ToRss and return it as your reader:

    func ToRss() io.Reader {
        buf := &bytes.Buffer{}
        io.WriteString(buf, "foo")
        return buf
    } 
    

    Playground link

    Alternatively you could start a new goroutine to write to the pipe and return it to be read from on the main goroutine. This method will avoid unnecessary buffering, but does introduce another goroutine.

    func ToRss() io.Reader {
       reader, writer := io.Pipe()
       go func() {
          io.WriteString(writer, "foo")
          writer.Close()
       }()
       return reader
    }
    

    Playground Link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错