Skip to content

JSON Request

Learn how to handle JSON request bodies in Iris.

Basic JSON Handling

go
package main

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

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

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

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

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

    app.Listen(":8080")
}

JSON Validation

go
type CreateUser struct {
    Name     string `json:"name" validate:"required,min=2"`
    Email    string `json:"email" validate:"required,email"`
    Age      int    `json:"age" validate:"required,gte=0,lte=130"`
    Password string `json:"password" validate:"required,min=8"`
}

app.Post("/validate", func(ctx iris.Context) {
    var user CreateUser
    if err := ctx.ReadJSON(&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": "JSON validated successfully",
        "user": user,
    })
})

Custom JSON Decoder

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

    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.