Response Recorder
Learn how to record and modify responses in Iris.
Basic Response Recording
go
package main
import "github.com/kataras/iris/v12"
func main() {
app := iris.New()
app.Get("/record", func(ctx iris.Context) {
// Create recorder
rec := ctx.Recorder()
// Write response
rec.Write([]byte("Hello World"))
rec.Writef(" from %s", "Iris")
// Get recorded body
body := rec.Body()
// Modify response
modified := strings.ToUpper(string(body))
// Write final response
ctx.WriteString(modified)
})
app.Listen(":8080")
}
Recording with Middleware
go
func recordMiddleware(ctx iris.Context) {
// Start recording
rec := ctx.Recorder()
// Continue to next handler
ctx.Next()
// Get recorded response
body := rec.Body()
status := rec.StatusCode()
headers := rec.Headers()
// Log response
ctx.Application().Logger().Infof(
"Response: Status=%d, Body=%s, Headers=%v",
status,
string(body),
headers,
)
}
app.Use(recordMiddleware)
Modifying Response
go
app.Get("/modify", func(ctx iris.Context) {
rec := ctx.Recorder()
// Write original response
ctx.JSON(iris.Map{
"message": "hello world",
})
// Get recorded response
var data map[string]interface{}
if err := json.Unmarshal(rec.Body(), &data); err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
// Modify response
data["modified"] = true
data["timestamp"] = time.Now()
// Write modified response
ctx.JSON(data)
})
Best Practices
Implementation:
- Record selectively
- Handle large responses
- Monitor memory
- Clean resources
- Handle errors
Performance:
- Buffer appropriately
- Monitor usage
- Handle timeouts
- Optimize recording
- Regular cleanup
Security:
- Validate modifications
- Monitor changes
- Handle sensitive data
- Control access
- Log modifications
Maintenance:
- Monitor usage
- Update handlers
- Regular testing
- Document changes
- Review performance