我正在嘗試在 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ì)破裂?
Golang 寫入 http 響應(yīng)會(huì)中斷輸入讀取嗎?
拉風(fēng)的咖菲貓
2021-09-13 15:30:56