dongyan8929 2014-03-16 17:19
浏览 141

如何使用Go标准库替换流中的字节?

I have a io.Reader which I get from http.Request.Body that reads a JSON byte slice from a server.

I would like to stream this to json.NewDecoder. However I would also like to intercept the JSON before it hits json.NewDecoder and substitute certain parts of it. For example, the JSON string contains empty hashes "{}" which I would like to remove due to a bug in the server's JSON output.

I am currently achieving my goal using json.Unmarshal but not using the JSON streaming parser:

data, _ := ioutil.ReadAll(r.Body)
data = bytes.Replace(data, []byte("{}"), "", -1)
json.Unmarshal(data, [my struct])

How can I achieve the same thing as above but using json.NewDecoder so I can save the many times the above code has to parse through r.Body's data? Here's some code using a pseudo function ReplaceStream(r io.Reader, old, new []byte):

reader := ReplaceStream(r.Body, []byte("{}"), "")
dec := json.NewDecoder(reader)
dec.Decode([my struct])

I know ReplaceStream might be fairly trivial to make, but is there anything in the standard library to do this that I am unaware of?

  • 写回答

1条回答 默认 最新

  • dqhgjay5753 2014-03-16 21:18
    关注

    My advice is to just treat that kind of message as a special case and avoid the extra parsing / substituting for all the other requests

    data, _ := ioutil.ReadAll(r.Body)
    // FIXME: overcome bug #12312 of json server 
    if data == `{"list": [{}]}` {
      return []
    } 
    // Normal datastruct ..
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序