简体   繁体   中英

How do I substitute bytes in a stream using Go standard library?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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