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

第59章 Iris 框架第59章:XML 响应

第59章 XML 响应

了解如何在 Iris 中发送 XML 响应。

基础 XML 响应

gopackage main import "github.com/kataras/iris/v12" type Person struct { XMLName xml.Name `xml:"person"` ID int `xml:"id,attr"` FirstName string `xml:"firstname"` LastName string `xml:"lastname"` Age int `xml:"age"` } func main() { app := iris.New() app.Get("/xml", func(ctx iris.Context) { person := Person{ ID: 1, FirstName: "John", LastName: "Doe", Age: 25, } ctx.XML(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

自定义 XML 头部

goapp.Get("/custom", func(ctx iris.Context) { ctx.ContentType("application/xml") ctx.Header("X-Custom", "value") data := struct { Message string `xml:"message"` }{ Message: "Hello World", } ctx.XML(data) }) 1
2
3
4
5
6
7
8
9
10
11
12

XML 集合

gotype Users struct { XMLName xml.Name `xml:"users"` Users []User `xml:"user"` } type User struct { ID int `xml:"id,attr"` Name string `xml:"name"` } app.Get("/users", func(ctx iris.Context) { users := Users{ Users: []User{ {ID: 1, Name: "John"}, {ID: 2, Name: "Jane"}, }, } ctx.XML(users) }) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

最佳实践

结构:使用正确的标签、遵循约定、记录模式定义、处理命名空间、验证输出。

性能:启用压缩、缓存响应、优化大小、监控编码、处理超时。

安全:验证输入、转义输出、设置头部、处理错误、监控使用情况。

维护:记录模式定义、更新结构、监控变更、定期测试、审查安全性。

评论 (0)