Binary Request
Learn how to handle binary request bodies in Iris.
Basic Binary Handling
go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Post("/binary", func(ctx iris.Context) {
data := ctx.GetBody()
ctx.JSON(iris.Map{
"size": len(data),
"received": true,
})
})
app.Listen(":8080")
}
Binary Upload with Size Limit
go
app.Post("/upload", iris.LimitRequestBodySize(32<<20), func(ctx iris.Context) {
data := ctx.GetBody()
// Process binary data
hash := sha256.Sum256(data)
ctx.JSON(iris.Map{
"size": len(data),
"hash": fmt.Sprintf("%x", hash),
})
})
Streaming Binary Data
go
app.Post("/stream", func(ctx iris.Context) {
reader := ctx.Request().Body
buffer := make([]byte, 1024)
content := []byte{}
for {
n, err := reader.Read(buffer)
if err != nil && err != io.EOF {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
if n == 0 {
break
}
content = append(content, buffer[:n]...)
}
ctx.JSON(iris.Map{
"size": len(content),
"received": true,
})
})
Best Practices
Validation:
- Check content type
- Validate size
- Handle formats
- Set limits
- Monitor usage
Security:
- Validate input
- Set size limits
- Scan content
- Monitor usage
- Handle errors
Performance:
- Use appropriate buffers
- Handle large data
- Monitor memory
- Implement timeouts
- Clean resources
Error Handling:
- Handle IO errors
- Validate content
- Log issues
- Document errors
- Test edge cases