2

I have the following code in my main.go

app.Post("/user", util.ValidateJson[model.User], func(c *fiber.Ctx) error {
    user := new(model.User)
    _ = c.BodyParser(&user)
    return c.Status(fiber.StatusCreated).JSON(model.Response{
        Data:   model.ToMap(*user)})
})

and a response struct

type Response struct {
    Data   fiber.Map    `json:"data"`
    Errors []*ErrorList `json:"errors"`
}

The issue I have is with the response returning the empty error list, which I want to avoid.

{
    "data": {
        "age": 1,
        "name": "ben"
    },
    "errors": null
}
Kaigo
  • 1,267
  • 2
  • 14
  • 33

1 Answers1

0

Use omitempty tag in response struct declaration. The omitempty tag is a struct field tag used in Go's encoding/json package to control the behavior of JSON serialization. When you apply the omitempty tag to a field in a struct, it indicates that the field should be omitted from the JSON representation if its value is empty or its zero value.

type Response struct {
    Data   fiber.Map    `json:"data"`
    Errors []*ErrorList `json:"errors,omitempty"` // Use the "omitempty" tag
}