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

第60章 在 Iris 框架中发送 YAML 响应

YAML 响应 学习如何在 Iris 中发送 YAML 响应。 基础 YAML 响应 gopackage main import ( "github.com/kataras/iris/v12" "gopkg.in/yaml.v3" ) type Config struct { Name string `yaml:"name"` Version string `yaml:"version"` Features []string `yaml:"features"` } func main() { app := iris.New() app.Get("/yaml", func(ctx iris.Context) { config := Config{ Name: "MyApp", Version: "1.0.0", Features: []string{ "Feature 1", "Feature 2", "Feature 3", }, } ctx.YAML(config) }) 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
30
31
32
自定义 YAML 编码 goapp.Get("/custom", func(ctx iris.Context) { data := map[string]interface{}{ "name": "John", "age": 25, "address": map[string]string{ "street": "123 Main St", "city": "New York", }, } yamlData, err := yaml.Marshal(data) if err != nil { ctx.StopWithError(iris.StatusInternalServerError, err) return } ctx.ContentType("application/x-yaml") ctx.Write(yamlData) }) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
YAML 集合 gotype Users struct { Users []User `yaml:"users"` } type User struct { ID int `yaml:"id"` Name string `yaml:"name"` } app.Get("/users", func(ctx iris.Context) { users := Users{ Users: []User{ {ID: 1, Name: "John"}, {ID: 2, Name: "Jane"}, }, } ctx.YAML(users) }) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
最佳实践 结构: - 使用正确的标签 - 遵循规范 - 记录格式 - 处理类型 - 校验输出 性能: - 启用压缩 - 缓存响应 - 优化尺寸 - 监控编码 - 处理超时 安全: - 校验输入 - 转义输出 - 设置请求头 - 处理错误 - 监控使用情况 维护: - 记录格式 - 更新结构 - 监控变更 - 定期测试 - 审查安全

评论 (0)