Revision control
Copy as Markdown
/*
* Compression Test
*
* This specification is needed to check how the compression is implemented.
*
* API version: 1.0.0
*/
package openapi
import (
"bytes"
"compress/gzip"
"compress/zlib"
"net/http"
"io"
"github.com/gin-gonic/gin"
)
type TestAPI struct {
}
// Post /v2/compression/roundtrip
// send the file and receive it back with various compression parameters
func (api *TestAPI) Roundtrip(c *gin.Context) {
content, err := io.ReadAll(c.Request.Body)
if err != nil {
c.String(http.StatusBadRequest, "Failed to read data from the request")
return
}
contentEncoding := c.GetHeader("Content-Encoding")
if contentEncoding == "gzip" {
// Gzip decompress
gz, err := gzip.NewReader(bytes.NewReader(content))
if err != nil {
c.String(http.StatusInternalServerError, "Failed to create gzip reader")
return
}
content, err = io.ReadAll(gz)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to decompress gzip data")
return
}
_ = gz.Close()
}
acceptEncoding := c.GetHeader("Accept-Encoding")
if acceptEncoding == "gzip, deflate" {
// Step1: Gzip compress
var gzipBuf bytes.Buffer
gz := gzip.NewWriter(&gzipBuf)
if _, err := gz.Write(content); err != nil {
c.String(http.StatusInternalServerError, "gzip compression failed")
return
}
_ = gz.Close();
// Step2: Deflate compress
var deflateBuf bytes.Buffer
def := zlib.NewWriter(&deflateBuf)
if _, err := def.Write(gzipBuf.Bytes()); err != nil {
c.String(http.StatusInternalServerError, "deflate compression failed")
return
}
_ = def.Close()
content = deflateBuf.Bytes()
c.Header("Content-Encoding", "gzip, deflate")
} // else send the data uncompressed
c.Data(http.StatusOK, "application/pdf", content)
}