亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我試圖改變來自流的字節,因為解碼,但它不起作用

我試圖改變來自流的字節,因為解碼,但它不起作用

Go
千萬里不及你 2022-06-06 17:51:30
我正在嘗試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

}


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號