I have a gin-gonic web app with somewhat MVC architecture. I created a couple of models, all of them embed one common struct:
type User struct {
ID int
Name string
}
type Admin struct {
User
Level int
}
... {
User
}
Now I want to store them in database in json format. The goal I want to accomplish is to code only one function/method that will marshal any model and will save save it into DB. This method must marshal all the fields of current model, not only from User struct, e.g. User must be marshaled into {id: 1, name: "zhora"}
, while Admin will go into {id: 1, name: "gena", level: 2}
.
Like this one:
func (i *User) Save() {
data, err := json.Marshal(i)
check(err)
if i.ID == 0 {
_, err = app.DB.Exec(`INSERT INTO users(data) VALUES ($1) `, string(data))
} else {
_, err = app.DB.Exec(`UPDATE users SET data = $1 WHERE id=$2`, string(data), i.ID)
}
check(err)
}
Right now I have to copy/paste this func
to every model file, changing only method receiver. Can this be avoided?
You may use one
func Save(d interface{})
like this:output:
for your case, use this one function for all types:
And call it like this:
And Yes, this is even simplifies call to
Save
to one parameter:output:
Now You may use this one function for all types:
And call it like this:
Effective Go: