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

第54章 Iris 框架教程:发送 Protocol Buffers 响应

Protocol Buffers 响应 了解如何在 Iris 框架中发送 Protocol Buffers 响应。 基本 Protobuf 响应 go package main import ( "github.com/kataras/iris/v12" "google.golang.org/protobuf/proto" ) // person.proto message Person { string name = 1; int32 age = 2; string email = 3; } func main() { app := iris.New() app.Get("/protobuf", func(ctx iris.Context) { person := &Person{ Name: "John Doe", Age: 25, Email: "john@example.com", } ctx.Protobuf(person) }) app.Listen(":8080") } 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
27
28
29
自定义 Protobuf 编码 go app.Get("/custom", func(ctx iris.Context) { data := &MyMessage{ Field1: "value1", Field2: 42, } // 手动序列化 bytes, err := proto.Marshal(data) if err != nil { ctx.StopWithError(iris.StatusInternalServerError, err) return } ctx.ContentType("application/x-protobuf") ctx.Write(bytes) }) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Protobuf 集合 go // people.proto message People { repeated Person people = 1; } app.Get("/people", func(ctx iris.Context) { people := &People{ People: []*Person{ {Name: "John", Age: 25}, {Name: "Jane", Age: 30}, }, } ctx.Protobuf(people) }) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
最佳实践 结构 定义 Schema、使用恰当的数据类型、为消息添加文档、处理版本兼容、验证输出 性能 启用压缩、缓存响应、监控数据大小、处理超时、优化编码 安全 验证输入、设置响应头、处理错误、监控使用情况、控制访问权限 维护 为 Schema 编写文档、更新消息定义、监控变更、定期测试、审查安全性

评论 (0)