Skip to content

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

  1. Implementation:

    • Support common formats
    • Handle preferences
    • Set proper headers
    • Document formats
    • Handle errors
  2. Performance:

    • Cache responses
    • Monitor usage
    • Handle timeouts
    • Optimize encoding
    • Regular cleanup
  3. Headers:

    • Set content type
    • Handle accept header
    • Configure caching
    • Monitor support
    • Handle errors
  4. Maintenance:

    • Document formats
    • Update handlers
    • Regular testing
    • Monitor changes
    • Review performance

Built with excellence by Hellenic Development, delivering enterprise-grade solutions.