进阶 www.iris-go.com 2026-10-20 02:39:14 · 14 阅读

第44章 Iris 框架中的 Binary 响应

二元响应 学习如何在 Iris 中发送二元响应。 基础二元响应 gopackage 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") }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
文件下载 goapp.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) })1
2
3
4
5
6
7
8
9
10
11
12
流式传输二元数据 goapp.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() } })1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
最佳实践 性能: 使用合适的缓冲区大小 启用压缩 流式传输大文件 监控内存使用 处理超时 安全性: 验证文件访问权限 设置正确的响应头 监控下载行为 处理错误 控制访问 响应头: 设置内容类型 设置附件类型 处理范围请求 配置缓存 启用压缩 错误处理: 检查文件是否存在 处理 IO 错误 监控超时 记录问题 清理资源

评论 (0)