我正在嘗試io.ReaderCloser使用可以傳遞給 JSON 解碼器的自定義閱讀器來(lái)包裝一個(gè),它在生產(chǎn)中將來(lái)自請(qǐng)求處理程序。我創(chuàng)建了以下import ( "io")// RemoveNull is a stream wrapper that should remove null bytes from the byte streamtype RemoveNull struct { Reader io.ReadCloser}// NewRemoveNullStream creates a new RemoveNull reader which passes the stream through a null check firstfunc NewRemoveNullStream(reader io.ReadCloser) RemoveNull { return RemoveNull{ Reader: reader, }}// Read wraps a Reader to remove null bytes in the streamfunc (null RemoveNull) Read(p []byte) (n int, err error) { n, err = null.Reader.Read(p) if err != nil { return n, err } nn := 0 for i := range p { if p[i] != 0 { p[nn] = p[i] nn++ } } p = p[:nn] // fmt.Println(p) i can see the value of p changing and all the null bytes are removed return n, nil}// Close closes the internal readerfunc (null RemoveNull) Close() error { return null.Close()}當(dāng)我運(yùn)行以下命令時(shí),我可以從 print 語(yǔ)句中看到確實(shí)刪除了所有空字節(jié),并且 len(p) == 所有預(yù)期好字節(jié)的大小。我寫了下面的測(cè)試,看看代碼是否按我的預(yù)期工作,這就是我意識(shí)到它不是的地方。從測(cè)試中我可以看到解碼時(shí)所有空字節(jié)仍然存在,但在 RemoveNull 閱讀器中我可以看到所有空字節(jié)都已從下劃線數(shù)組中刪除。關(guān)于什么是錯(cuò)的以及如何實(shí)現(xiàn)從流中刪除字節(jié)以避免讓解碼器解碼空字節(jié)的目標(biāo)的任何想法?
我試圖改變來(lái)自流的字節(jié),因?yàn)榻獯a,但它不起作用
千萬(wàn)里不及你
2022-06-06 17:51:30