dongwa3808 2018-12-22 10:33
浏览 56


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.

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().

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. Then the buffered bytes would be returned on the next call to Read().

This is what I came up with:

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 ?

  • 写回答

1条回答 默认 最新

  • douxing9641 2018-12-22 13:06

    A simple method is using io.Pipe.

    func ScannerToReader(scanner *bufio.Scanner) io.Reader {
        reader, writer := io.Pipe()
        go func() {
            defer writer.Close()
            for scanner.Scan() {
        return reader
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 怎样采集或者其它途径拿到全国最新个体工商户数据
  • ¥20 我是一名大学生,想学习java是自学还是报培训班呢
  • ¥15 pycharm该如何爬取网易云歌曲下的评论?
  • ¥15 java调用sap webservice问题
  • ¥20 如何完全复现何恺明resnet论文里的结果,有代码吗,获得论文中的结果(如下图)
  • ¥15 mysql如果表行行数小于1000条还需要分区吗
  • ¥20 有关matlab自定义特殊算符的问题
  • ¥15 第15届蓝桥杯选拔赛斗鱼养殖场
  • ¥15 在vivado的FIFO使用中,FIFO有没有提供可以输出内部存储空间状态的端口?
  • ¥15 C++ QT内存数据匹配对比指导