doutan5844 2018-09-06 13:45
浏览 62
已采纳

GoLang链接io.Reader

I'm trying to implement a proxy pattern to chain transformations on io.Reader, in order to handle chunk of bytes efficiently.

  1. We cannot use pointers on receivers, so my solution seem not very efficient

  2. The code below say "process take too long"

Complete example at: https://play.golang.org/p/KhM0VXLq4CO

b := bytes.NewBufferString(text)
t := transformReaderHandler(*b)
readByChunk(t)

type transformReaderHandler bytes.Buffer

func (t transformReaderHandler) Read(p []byte) (n int, err error) {
    n, err = (*bytes.Buffer)(&t).Read(p)
    //if n > 0 {
    //  Do Something on the chunk
    //}
    return
}

Do you have any more efficient (memory efficient, computationally efficient) solution ?

Why do this code is not working ?

EDIT: The implementation of @svsd solution : https://play.golang.org/p/VUpJcyKLB6D

package main

import (
    "io"
    "fmt"
    "bytes"
)

const text = "Reaaaaally long and complex text to read in chunk"

func main() {
    b := bytes.NewBufferString(text)

    t := (*transformReaderHandler)(b)

    readByChunk(t)
}

type transformReaderHandler bytes.Buffer

func (t *transformReaderHandler) Read(p []byte) (n int, err error) {
    n, err = (*bytes.Buffer)(t).Read(p)
    if n > 0 {
        p[0] = 'X'
    }
    return
}

func readByChunk(r io.Reader) {
    var p = make([]byte, 4)

    for {
        n, err := r.Read(p)
        if err == io.EOF {
            break
        }
        fmt.Println(string(p[:n]))
    }
}
  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 类的继承,综合输出学生信息并析构
      • ¥15 js 使用contenteditable属性模拟富文本框的时候如何定位光标到指定位置
      • ¥15 怎么激活组态王的Touchvew菜单和Touchmak 菜单
      • ¥15 Meta分析中,如何在只有样本量的情况下用cma处理效应量r值。
      • ¥15 关于#OpenCV#的问题,如何解决?(语言-qt|开发工具-visual studio)
      • ¥15 centos环境中引入jsoncpp后,编译工程报错,找不到基本库。
      • ¥15 vue3为什么请求在这边获取不到数据呢(关键词-select)
      • ¥20 Multisim仿真设计三路智力抢答装置
      • ¥15 用UML制作简单的语音计算机
      • ¥20 用socket实现ping遇到的问题