Skip to content

Binary Response

Learn how to send binary responses in Iris.

Basic Binary Response

go
package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()

    app.Get("/binary", func(ctx iris.Context) {
        data := []byte{0x48, 0x65, 0x6C, 0x6C, 0x6F} // "Hello" in hex
        ctx.ContentType("application/octet-stream")
        ctx.Write(data)
    })

    app.Listen(":8080")
}

File Download

go
app.Get("/download", func(ctx iris.Context) {
    // Read file
    data, err := os.ReadFile("file.bin")
    if err != nil {
        ctx.StopWithError(iris.StatusInternalServerError, err)
        return
    }

    ctx.ContentType("application/octet-stream")
    ctx.Header("Content-Disposition", `attachment; filename="file.bin"`)
    ctx.Write(data)
})

Streaming Binary Data

go
app.Get("/stream", func(ctx iris.Context) {
    file, err := os.Open("large.bin")
    if err != nil {
        ctx.StopWithError(iris.StatusInternalServerError, err)
        return
    }
    defer file.Close()

    ctx.ContentType("application/octet-stream")
    ctx.Header("Content-Disposition", `attachment; filename="large.bin"`)

    buffer := make([]byte, 1024)
    for {
        n, err := file.Read(buffer)
        if err == io.EOF {
            break
        }
        if err != nil {
            ctx.StopWithError(iris.StatusInternalServerError, err)
            return
        }

        ctx.Write(buffer[:n])
        ctx.ResponseWriter().Flush()
    }
})

Best Practices

  1. Performance:

    • Use appropriate buffer sizes
    • Enable compression
    • Stream large files
    • Monitor memory usage
    • Handle timeouts
  2. Security:

    • Validate file access
    • Set proper headers
    • Monitor downloads
    • Handle errors
    • Control access
  3. Headers:

    • Set content type
    • Set disposition
    • Handle ranges
    • Configure caching
    • Use compression
  4. Error Handling:

    • Check file existence
    • Handle IO errors
    • Monitor timeouts
    • Log issues
    • Clean resources

Built with excellence by Hellenic Development, delivering enterprise-grade solutions.