Search code examples
gobuffalo

Respond only few fields from the model


Below is my Advertiser Model -

type Advertiser struct {
    ID            int       `json:"id" db:"id"`
    CreatedAt     time.Time `json:"created_at" db:"created_at"`
    UpdatedAt     time.Time `json:"updated_at" db:"updated_at"`
    Name          string    `json:"name" db:"name"`
    Email         string    `json:"email" db:"email"`
    ContactNumber string    `json:"contact_number" db:"contact_number"`
}

I have generated the Advertiser Resource and by default, it had brought-in the actions.

Now, in AdvertiserList action, I need all these fields to do some or the other calculation. But, finally, I would like to only respond with Name, Email and ContactNumber fields.

Remember, this is a List action, which means, we have an array of Advertiser.

Right now, my action does below-

func (v AdvertisersResource) List(c buffalo.Context) error {
    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return errors.WithStack(errors.New("no transaction found"))
    }

    advertisers := &models.Advertisers{}

    q := tx.PaginateFromParams(c.Params())
    if err := q.All(advertisers); err != nil {
        return errors.WithStack(err)
    }

    c.Set("pagination", q.Paginator)

    return c.Render(200, r.JSON(advertisers))
}

Solution

  • I'm not sure if I understood your question correctly. However when marshaling to json if you have fields with tags json:"-" then that value is not returned.