1

I used gorm library.

gorm support struct data inserting in DB and returning.

But my service do not always need every struct member.

For Example;

/Address => this api will return only user address.

But orm return all struct memeber.

like this.

    type User {
      Name string
      Address string
    }

    db.find(&user)

    apiResponse(200,user)

So I always make serializer code for specific api returning shape.

    type Serializer  {
       Address string
    }

    func MakeSerializer(User u) Serializer {
            return Serilizer { Address: u.Address }
    }

But Above Code is not good.

Cause all most Api Return Shape is vary. So I will need enormous serilzer code.

Show me best practice for this problem.

Thank u

Yenos
  • 87
  • 10

2 Answers2

3

You can use json:"-" tag to remove field from JSON serialization of your structure, but I prefer to use different structures for the database layer and rest interface.

Something like this:

type Construction struct {
    gorm.Model

    Name        string `gorm:"size:30;unique_index"`
    Description string `gorm:"size:100"`
}

type Construction struct {
    Id          uint   `json:"Id"`
    Name        string `json:"Name"`
    Description string `json:"Description"`
    Additions   string `json:"Additions"` 
}

func setConstructionFields(ct types.Construction, construction *models.Construction, additions string) types.Construction {
    ct.Name = construction.Name
    ct.Description = construction.Description
    ct.Additions = additions
    return ct
}

In this case you need to have two structures instead one and you need to write a function to transform one struct ot another, but you have more flexibility when you working with your data and your database layer will be less connected to rest service layer.

ceth
  • 44,198
  • 62
  • 180
  • 289
  • Thanks for your answer! In your code case, api response data is more than database getting data. but my code case, opposite situation. Than am I use `json "-" ` – Yenos Jan 06 '19 at 23:38
  • something like: type User { Name string Address string `json:"-"` } right? – Yenos Jan 06 '19 at 23:39
  • It is just example. Your `models.Construction` can have additional fields and at the same time can skip some of them. Moreover you can have absolutely different set of fields. And it is general idea: you can change REST interface and all you need to change - this function which set the mapping between REST and DB layers. – ceth Jan 07 '19 at 02:22
2

I suppose that you serializing your responses into the JSON. This solves your problem. In order to always skip the field serialization, just add json:"-".

type User {
   Name string
   Address string `json:"-"`
}
zdebra
  • 948
  • 8
  • 22