Gzip Request
Learn how to handle Gzip compressed requests in Iris.
Basic Gzip Handling
go
package main
import (
"compress/gzip"
"io"
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
app.Post("/gzip", func(ctx iris.Context) {
if ctx.GetHeader("Content-Encoding") != "gzip" {
ctx.StopWithStatus(iris.StatusBadRequest)
return
}
reader, err := gzip.NewReader(ctx.Request().Body)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
defer reader.Close()
data, err := io.ReadAll(reader)
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
ctx.JSON(iris.Map{
"decompressed_size": len(data),
"content": string(data),
})
})
app.Listen(":8080")
}
JSON with Gzip
go
type Message struct {
Text string `json:"text"`
Time int64 `json:"time"`
}
app.Post("/json-gzip", func(ctx iris.Context) {
if ctx.GetHeader("Content-Encoding") != "gzip" {
ctx.StopWithStatus(iris.StatusBadRequest)
return
}
reader, err := gzip.NewReader(ctx.Request().Body)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
defer reader.Close()
var msg Message
if err := json.NewDecoder(reader).Decode(&msg); err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
ctx.JSON(iris.Map{
"received": msg,
})
})
Large File Upload with Gzip
go
app.Post("/upload-gzip", iris.LimitRequestBodySize(32<<20), func(ctx iris.Context) {
if ctx.GetHeader("Content-Encoding") != "gzip" {
ctx.StopWithStatus(iris.StatusBadRequest)
return
}
reader, err := gzip.NewReader(ctx.Request().Body)
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
defer reader.Close()
// Create temporary file
tempFile, err := os.CreateTemp("", "upload-*.dat")
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
defer tempFile.Close()
// Copy decompressed data to file
written, err := io.Copy(tempFile, reader)
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
ctx.JSON(iris.Map{
"decompressed_size": written,
"filename": tempFile.Name(),
})
})
Best Practices
Validation:
- Check content encoding
- Validate compression
- Set size limits
- Handle formats
- Monitor usage
Performance:
- Use appropriate buffers
- Handle large data
- Monitor memory
- Implement timeouts
- Clean resources
Security:
- Validate input
- Set size limits
- Check content
- Monitor usage
- Handle errors
Error Handling:
- Handle compression errors
- Validate content
- Log issues
- Document errors
- Test edge cases