Skip to content

YAML Response

Learn how to send YAML responses in Iris.

Basic YAML Response

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.Get("/yaml", func(ctx iris.Context) {
        config := Config{
            Name:    "MyApp",
            Version: "1.0.0",
            Features: []string{
                "Feature 1",
                "Feature 2",
                "Feature 3",
            },
        }

        ctx.YAML(config)
    })

    app.Listen(":8080")
}

Custom YAML Encoding

go
app.Get("/custom", func(ctx iris.Context) {
    data := map[string]interface{}{
        "name": "John",
        "age":  25,
        "address": map[string]string{
            "street": "123 Main St",
            "city":   "New York",
        },
    }

    yamlData, err := yaml.Marshal(data)
    if err != nil {
        ctx.StopWithError(iris.StatusInternalServerError, err)
        return
    }

    ctx.ContentType("application/x-yaml")
    ctx.Write(yamlData)
})

YAML Collection

go
type Users struct {
    Users []User `yaml:"users"`
}

type User struct {
    ID   int    `yaml:"id"`
    Name string `yaml:"name"`
}

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

    ctx.YAML(users)
})

Best Practices

  1. Structure:

    • Use proper tags
    • Follow conventions
    • Document format
    • Handle types
    • 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 format
    • Update structure
    • Monitor changes
    • Regular testing
    • Review security

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