如何连接io.Reader和io.Writer? [英] How do I connect io.Reader and io.Writer?
问题描述
我正在编写一个长期运行的任务,该任务多次从mongodb(使用mgo)获取.然后使用此模块将其写入xlsx文件.然后使用os.Open
再次读取它,然后将其存储到我的ftp服务器中.
I'm writing a long running task which fetch from mongodb (using mgo) multiple times. Then write it to an xlsx file using this module. Then read it again using os.Open
then store it to my ftp server.
Stor
函数消耗了我的大量内存,因此我认为应该有一种不保存文件,而是将我的数据从xlsx.Write传递到ftp.Store的方法. (如果可以同时进行流传输,那将是完美的,因为在将它们发送到Stor函数之前,不必将所有文档都保留在服务器的内存中)
Stor
function consume my memory so much, So I think there should be a way not to save file but pass my data from xlsx.Write to ftp.Store directly. (If I can stream simultaneously would be perfect because I don't have to hold all of my documents in server's memory before send them to Stor function)
这些是函数的原型
func (f *File) Write(writer io.Writer) (err error)
xlsl
func (ftp *FTP) Stor(path string, r io.Reader) (err error)
ftp
推荐答案
您要使用 io.Pipe .您可以这样做:
You want to use io.Pipe. You can do:
reader, writer := io.Pipe()
errChan := make(chan error)
go func() {
errChan <- myFTP.Stor(path, reader)
}()
err := myXLS.Write(writer)
// handle err
err = <-errChan
// handle err
如果xlsx.Write
返回错误而不关闭编写器,则可能要writer.CloseWithError(err)
.
You might want to writer.CloseWithError(err)
if xlsx.Write
returns an error without closing the writer.
这篇关于如何连接io.Reader和io.Writer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!