我正在嘗試io.ReaderCloser使用可以傳遞給 JSON 解碼器的自定義閱讀器來包裝一個,它在生產中將來自請求處理程序。我創建了以下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()}當我運行以下命令時,我可以從 print 語句中看到確實刪除了所有空字節,并且 len(p) == 所有預期好字節的大小。我寫了下面的測試,看看代碼是否按我的預期工作,這就是我意識到它不是的地方。從測試中我可以看到解碼時所有空字節仍然存在,但在 RemoveNull 閱讀器中我可以看到所有空字節都已從下劃線數組中刪除。關于什么是錯的以及如何實現從流中刪除字節以避免讓解碼器解碼空字節的目標的任何想法?
1 回答

DIEA
TA貢獻1820條經驗 獲得超3個贊
您的 Read 實現中存在錯誤。它在 io.EOF 的情況下過早終止,其中同時存在錯誤和數據。它返回讀取的錯誤字節數。分配切片的最后一部分也沒有意義,因為它不會更新傳遞給函數的切片。
嘗試這個:
func (null RemoveNull) Read(p []byte) (n int, err error) {
n, err = null.Reader.Read(p)
nn := 0
for i:=0;i<n;i++ {
if p[i] != 0 {
p[nn] = p[i]
nn++
}
}
return nn, err
}
- 1 回答
- 0 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消