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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制