Failed to decode gzip

I’m stuck on Stage #CR8 “Gzip compression”

Here are my logs:

remote: [tester::#CR8] Running tests for Stage #CR8 (HTTP Compression - Gzip compression)
remote: [tester::#CR8] Running program
remote: [tester::#CR8] $ ./your_program.sh
remote: [tester::#CR8] Connected to localhost port 4221
remote: [tester::#CR8] $ curl -v http://localhost:4221/echo/apple -H "Accept-Encoding: gzip"
remote: [your_program] new connection from [::1]:50046
remote: [tester::#CR8] > GET /echo/apple HTTP/1.1
remote: [tester::#CR8] > Host: localhost:4221
remote: [tester::#CR8] > Accept-Encoding: gzip
remote: [tester::#CR8] >
remote: [tester::#CR8] Sent bytes: "GET /echo/apple HTTP/1.1\r\nHost: localhost:4221\r\nAccept-Encoding: gzip\r\n\r\n"
remote: [tester::#CR8] Received bytes: "HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: 21\r\n\r\n\x1f\x8b\b\x00\x00\x00\x00\x00\x00\xffJ,(\xc8I\x05\x00\x00\x00\xff\xff"
remote: [tester::#CR8] < HTTP/1.1 200 OK
remote: [tester::#CR8] < Content-Encoding: gzip
remote: [tester::#CR8] < Content-Length: 21
remote: [tester::#CR8] <
remote: [tester::#CR8] < <Binary Content>
remote: [tester::#CR8] <
remote: [tester::#CR8] Received response with 200 status code
remote: [tester::#CR8] ✓ Content-Encoding header is present
remote: [tester::#CR8] ✓ Content-Length header is present
remote: [tester::#CR8] Failed to decode gzip: Failed to decompress data: unexpected EOF
remote: [tester::#CR8] Test failed
remote: [tester::#CR8] Terminating program
remote: [tester::#CR8] Program terminated successfully

And here’s a snippet of my code:

		str := strings.Replace(req.Path, "/echo/", "", 1)

		buf := bytes.NewBuffer(nil)
		zw := gzip.NewWriter(buf)
		defer zw.Close()

		_, writeErr := zw.Write([]byte(str))
		if writeErr != nil {
			panic(writeErr)
		}
		zw.Flush()

		respBuf := bytes.NewBufferString("HTTP/1.1 200 OK\r\n")
		respBuf.WriteString("Content-Encoding: gzip\r\n")
		respBuf.WriteString(fmt.Sprintf("Content-Length: %d\r\n", buf.Len()))
		respBuf.WriteString("\r\n")
		respBuf.Write(buf.Bytes())

		conn.Write(respBuf.Bytes())

When I use Postman to hit the endpoint, Postman is able to unzip the body and displays the content. However, when I do curl http://localhost:4221/echo/banana -H "Accept-Encoding: gzip" | gunzip -c, I get gunzip: (stdin): unexpected end of file.

Did I miss anything?

Thank you!

Hey @ungsophy, looks like your gzipped data is incomplete: the footer is missing.

This happens due to defer zw.Close(). You’ll need to explicitly call zw.Close() before reading from the buffer.

Let me know if you’d like further clarification!

Thank you so much @andy1li. Calling zw.Close() before reading from the buffer fixes the issue.