Skip to content

XML Response

Learn how to send XML responses in Iris.

Basic XML Response

go
package main

import "github.com/kataras/iris/v12"

type Person struct {
    XMLName   xml.Name `xml:"person"`
    ID        int      `xml:"id,attr"`
    FirstName string   `xml:"firstname"`
    LastName  string   `xml:"lastname"`
    Age       int      `xml:"age"`
}

func main() {
    app := iris.New()

    app.Get("/xml", func(ctx iris.Context) {
        person := Person{
            ID:        1,
            FirstName: "John",
            LastName:  "Doe",
            Age:       25,
        }

        ctx.XML(person)
    })

    app.Listen(":8080")
}

Custom XML Header

go
app.Get("/custom", func(ctx iris.Context) {
    ctx.ContentType("application/xml")
    ctx.Header("X-Custom", "value")

    data := struct {
        Message string `xml:"message"`
    }{
        Message: "Hello World",
    }

    ctx.XML(data)
})

XML Collection

go
type Users struct {
    XMLName xml.Name `xml:"users"`
    Users   []User   `xml:"user"`
}

type User struct {
    ID   int    `xml:"id,attr"`
    Name string `xml:"name"`
}

app.Get("/users", func(ctx iris.Context) {
    users := Users{
        Users: []User{
            {ID: 1, Name: "John"},
            {ID: 2, Name: "Jane"},
        },
    }

    ctx.XML(users)
})

Best Practices

  1. Structure:

    • Use proper tags
    • Follow conventions
    • Document schema
    • Handle namespaces
    • Validate output
  2. Performance:

    • Enable compression
    • Cache responses
    • Optimize size
    • Monitor encoding
    • Handle timeouts
  3. Security:

    • Validate input
    • Escape output
    • Set headers
    • Handle errors
    • Monitor usage
  4. Maintenance:

    • Document schema
    • Update structure
    • Monitor changes
    • Regular testing
    • Review security

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