Skip to content

XML Request

Learn how to handle XML request bodies in Iris.

Basic XML Handling

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.Post("/xml", func(ctx iris.Context) {
        var person Person
        if err := ctx.ReadXML(&person); err != nil {
            ctx.StopWithError(iris.StatusBadRequest, err)
            return
        }

        ctx.JSON(iris.Map{
            "received": person,
        })
    })

    app.Listen(":8080")
}

XML Validation

go
type User struct {
    XMLName  xml.Name `xml:"user"`
    Username string   `xml:"username" validate:"required,min=3"`
    Email    string   `xml:"email" validate:"required,email"`
    Age      int      `xml:"age" validate:"gte=0,lte=130"`
}

app.Post("/validate", func(ctx iris.Context) {
    var user User
    if err := ctx.ReadXML(&user); err != nil {
        ctx.StopWithError(iris.StatusBadRequest, err)
        return
    }

    // Validate struct
    if err := validate.Struct(user); err != nil {
        ctx.StopWithProblem(iris.StatusBadRequest, iris.NewProblem().
            Title("Validation Error").
            DetailErr(err))
        return
    }

    ctx.JSON(iris.Map{
        "message": "XML validated successfully",
        "user": user,
    })
})

Custom XML Decoder

go
app.Post("/custom", func(ctx iris.Context) {
    decoder := xml.NewDecoder(ctx.Request().Body)
    decoder.Strict = false
    decoder.AutoClose = xml.HTMLAutoClose
    decoder.Entity = xml.HTMLEntity

    var data interface{}
    if err := decoder.Decode(&data); err != nil {
        ctx.StopWithError(iris.StatusBadRequest, err)
        return
    }

    ctx.JSON(iris.Map{
        "data": data,
    })
})

Best Practices

  1. Validation:

    • Validate schema
    • Check required fields
    • Handle types
    • Set limits
    • Document requirements
  2. Security:

    • Validate input
    • Handle entities
    • Prevent XXE
    • Set size limits
    • Monitor usage
  3. Performance:

    • Use appropriate decoder
    • Handle large documents
    • Monitor memory
    • Implement timeouts
    • Clean resources
  4. Error Handling:

    • Provide clear messages
    • Handle validation errors
    • Log issues
    • Document errors
    • Test edge cases

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