Skip to content

MessagePack Response

Learn how to send MessagePack responses in Iris.

Basic MessagePack Response

go
package main

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

type User struct {
    ID    int    `msgpack:"id"`
    Name  string `msgpack:"name"`
    Email string `msgpack:"email"`
}

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

    app.Get("/msgpack", func(ctx iris.Context) {
        user := User{
            ID:    1,
            Name:  "John Doe",
            Email: "john@example.com",
        }

        ctx.MessagePack(user)
    })

    app.Listen(":8080")
}

Custom MessagePack 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",
        },
    }

    ctx.MessagePack(data)
})

MessagePack Collection

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

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

    ctx.MessagePack(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
    • Set headers
    • Handle errors
    • Monitor usage
    • Control access
  4. Maintenance:

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

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