进阶 www.iris-go.com 2026-10-20 02:39:14 · 13 阅读
第58章 Iris 框架中的 Text Response 文本响应
Text Response 文本响应
学习如何在 Iris 中发送文本响应。
基础 Text Response
gopackage main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Get("/text", func(ctx iris.Context) {
ctx.Text("Hello World")
})
app.Get("/formatted", func(ctx iris.Context) {
name := "John"
age := 25
ctx.Writef("Name: %s, Age: %d", name, age)
})
app.Listen(":8080")
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Content Type 内容类型
goapp.Get("/custom", func(ctx iris.Context) {
ctx.ContentType("text/plain; charset=UTF-8")
ctx.WriteString("Custom content type")
})1
2
3
4
Status Code 状态码
goapp.Get("/status", func(ctx iris.Context) {
ctx.StatusCode(iris.StatusOK)
ctx.Text("Success!")
})1
2
3
4
最佳实践 Best Practices
Content Type 内容类型:
- 设置合适的字符集
- 使用正确的 MIME 类型
- 正确处理编码
- 考虑客户端需求
- 文档化要求
性能 Performance:
- 优化响应大小
- 启用压缩
- 尽可能使用缓存
- 监控响应时间
- 处理超时情况
错误处理 Error Handling:
- 设置正确的状态码
- 提供清晰的信息
- 适当记录错误
- 处理边缘情况
- 验证输入
安全性 Security:
- 净化输出
- 验证输入
- 设置安全头部
- 监控响应
- 处理敏感数据