简体   繁体   English

从扫描仪转换为io.Reader的惯用方式

[英]Idiomatic way to convert from a scanner to a io.Reader

I recently ran into this issue of how to read from a CSV file, apply some transformation to every line and write to a HTTP request. 我最近遇到了这样一个问题:如何从CSV文件读取,对每行进行一些转换并写入HTTP请求。

The problem I was faced with was how to convert from a line-by-line reader which returns an arbitrary number of bytes (like a Scanner) to a byte reader, which returns a fixed amount of bytes at every call to Read(). 我面临的问题是如何从逐行读取器(它返回任意数量的字节(如扫描仪))转换为字节读取器,该读取器在每次调用Read()时都返回固定数量的字节。

The best solution I came up with is to build a custom io.Reader that would read from the Scanner and buffer bytes locally if they wouldn't fit. 我想到的最好的解决方案是构建一个自定义io.Reader,它将从扫描器读取并在不适合的情况下在本地缓冲字节。 Then the buffered bytes would be returned on the next call to Read(). 然后,在下次调用Read()时将返回缓冲的字节。

This is what I came up with: https://gist.github.com/paulsc/6a0bf30a2a8d898f7a8086aedf6af1e1 这是我想出的: https : //gist.github.com/paulsc/6a0bf30a2a8d898f7a8086aedf6af1e1

Intuitively, this feels like the wrong solution, because the code seems like a fairly low-level solution that might already be in the standard library. 直觉上,这感觉像是一个错误的解决方案,因为代码似乎是一个相当底层的解决方案,可能已经在标准库中了。

Is there a better way, more idiomatic to do this with standard go components ? 有没有更好的方法,更惯用标准go组件呢?

A simple method is using io.Pipe . 一种简单的方法是使用io.Pipe

func ScannerToReader(scanner *bufio.Scanner) io.Reader {
    reader, writer := io.Pipe()


    go func() {
        defer writer.Close()
        for scanner.Scan() {
            writer.Write(scanner.Bytes())
        }
    }()

    return reader
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM