Skip to content

YAML Request

Learn how to handle YAML request bodies in Iris.

Basic YAML Handling

go
package main

import (
    "github.com/kataras/iris/v12"
    "gopkg.in/yaml.v3"
)

type Config struct {
    Name     string   `yaml:"name"`
    Version  string   `yaml:"version"`
    Features []string `yaml:"features"`
}

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

    app.Post("/yaml", func(ctx iris.Context) {
        var config Config
        if err := ctx.ReadYAML(&config); err != nil {
            ctx.StopWithError(iris.StatusBadRequest, err)
            return
        }

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

    app.Listen(":8080")
}

YAML Validation

go
type Service struct {
    Name     string `yaml:"name" validate:"required"`
    Port     int    `yaml:"port" validate:"required,min=1024,max=65535"`
    Replicas int    `yaml:"replicas" validate:"required,min=1"`
}

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

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

    ctx.JSON(iris.Map{
        "message": "YAML validated successfully",
        "service": service,
    })
})

Custom YAML Decoder

go
app.Post("/custom", func(ctx iris.Context) {
    decoder := yaml.NewDecoder(ctx.Request().Body)
    decoder.KnownFields(true)

    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
    • Set size limits
    • Check structure
    • Monitor usage
    • Handle errors
  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.