Content Negotiation
Learn how to implement content negotiation in Iris.
Basic Content Negotiation
go
package main
import "github.com/kataras/iris/v12"
type User struct {
Name string `json:"name" xml:"name"`
Age int `json:"age" xml:"age"`
}
func main() {
app := iris.New()
app.Get("/user", func(ctx iris.Context) {
user := User{
Name: "John Doe",
Age: 25,
}
ctx.Negotiation().JSON().XML()
ctx.Negotiate(user)
})
app.Listen(":8080")
}
Multiple Formats
go
app.Get("/data", func(ctx iris.Context) {
data := iris.Map{
"message": "Hello World",
}
ctx.Negotiation().
JSON().
XML().
YAML().
MsgPack().
Any("text/plain", func(ctx iris.Context) {
ctx.Text("Plain text response")
})
ctx.Negotiate(data)
})
Custom Negotiation
go
app.Get("/custom", func(ctx iris.Context) {
data := getData()
ctx.Negotiation().
JSON(func(ctx iris.Context) {
ctx.JSON(data)
}).
XML(func(ctx iris.Context) {
ctx.XML(data)
}).
MsgPack(func(ctx iris.Context) {
ctx.MessagePack(data)
})
ctx.Negotiate(nil)
})
Best Practices
Implementation:
- Support common formats
- Handle preferences
- Set proper headers
- Document formats
- Handle errors
Performance:
- Cache responses
- Monitor usage
- Handle timeouts
- Optimize encoding
- Regular cleanup
Headers:
- Set content type
- Handle accept header
- Configure caching
- Monitor support
- Handle errors
Maintenance:
- Document formats
- Update handlers
- Regular testing
- Monitor changes
- Review performance