慕运维8079593
其他答案概述了如何使用 io.Pipe。这个答案显示了更多细节,特别是关于错误处理。func gzFileReader(fname string) (io.ReadCloser, error) { f, err := os.Open(fname) if err != nil { return nil, err } // Use io.Pipe and a goroutine to create reader // on data written by the appliation. r, w := io.Pipe() go func() { // Always close the file. defer f.Close() // Copy file through gzip to pipe writer. gzw := gzip.NewWriter(w) _, err := io.Copy(gzw, f) // Use CloseWithError to propgate errors back to // the main goroutine. if err != nil { w.CloseWithError(err) return } // Flush the gzip writer. w.CloseWithError(gzw.Close()) }() return r, nil}使用这样的功能:body, err := gzFileReader("example.txt")if err != nil { log.Fatal(err)}defer body.Close()req, err := http.NewRequest("POST", "http://example.com/", body)if err != nil { log.Fatal(err)}req.Header.Set("Content-Encoding", "gzip")resp, err := http.DefaultClient.Do(req)