第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Golang 寫入 http 響應(yīng)會(huì)中斷輸入讀取嗎?

Golang 寫入 http 響應(yīng)會(huì)中斷輸入讀取嗎?

Go
拉風(fēng)的咖菲貓 2021-09-13 15:30:56
我正在嘗試在 Go 中編寫一個(gè)小型 web 應(yīng)用程序,用戶可以在其中以多部分形式上傳 gzipped 文件。應(yīng)用程序解壓縮并解析文件并將一些輸出寫入響應(yīng)。但是,當(dāng)我開始寫入響應(yīng)時(shí),我不斷遇到輸入流看起來已損壞的錯(cuò)誤。不寫入響應(yīng)可以解決問題,就像從非 gzipped 輸入流讀取一樣。這是一個(gè)示例 http 處理程序:func(w http.ResponseWriter, req *http.Request) {//Get an input stream from the multipart reader//and read it using a scannermultiReader, _ := req.MultipartReader()part, _ := multiReader.NextPart()gzipReader, _ := gzip.NewReader(part)scanner := bufio.NewScanner(gzipReader)//Strings read from the input stream go to this channel     inputChan := make(chan string, 1000)//Signal completion on this channel donechan := make(chan bool, 1)//This goroutine just reads text from the input scanner//and sends it into the channel go func() {    for scanner.Scan() {        inputChan <- scanner.Text()    }           close(inputChan)}()//Read lines from input channel. They all either start with #//or have ten tab-separated columnsgo func() {    for line := range inputChan {        toks := strings.Split(line, "\t")        if len(toks) != 10 && line[0] != '#' {            panic("Dang.")        }    }    donechan <- true }()//periodically write some random text to the responsego func() {    for {        time.Sleep(10*time.Millisecond)             w.Write([]byte("write\n some \n output\n"))    }}()//wait until we're done to return<-donechan}奇怪的是,這段代碼每次都會(huì)發(fā)生恐慌,因?yàn)樗偸怯龅缴儆?10 個(gè)標(biāo)記的行,盡管每次都在不同的位置。注釋掉寫入響應(yīng)的行可以解決問題,就像從非 gzip 輸入流中讀取一樣。我錯(cuò)過了一些明顯的東西嗎?如果從 gzip 文件而不是純文本格式的文件中讀取,為什么寫入響應(yīng)會(huì)中斷?為什么它會(huì)破裂?
查看完整描述

1 回答

?
交互式愛情

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊

HTTP 協(xié)議不是全雙工的:它是基于請(qǐng)求-響應(yīng)的。您應(yīng)該只在完成讀取輸入后發(fā)送輸出。


在您的代碼中,您在頻道上使用forwith range。這將嘗試讀取通道直到它關(guān)閉,但你永遠(yuǎn)不會(huì)關(guān)閉inputChan.


如果您從不 close inputChan,則永遠(yuǎn)不會(huì)到達(dá)以下行:


donechan <- true 

因此從donechan塊接收:


<-donechan

您必須在inputChan達(dá)到 EOF 時(shí)關(guān)閉:


go func() {

    for scanner.Scan() {

        inputChan <- scanner.Text()

    }       

    close(inputChan) // THIS IS NEEDED

}()


查看完整回答
反對(duì) 回復(fù) 2021-09-13
  • 1 回答
  • 0 關(guān)注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)