I'm trying to create a generic interface in go for models I wish to use in my api.
type Model interface {
Create(interface{}) (int64, error)
Update(string, interface{}) (error)
}
And I have a personModel which implements it:
type Person struct {
Id int `json:"id"`
FirstName string `json:"firstName"`
}
type PersonModel struct {
Db *sql.DB
}
func (model *PersonModel) Create(personStruct person) (int64, error) {
// do database related stuff to create the person from the struct
}
func (model *PersonModel) Update(id string, personStruct person) (error) {
// do database related stuff to update the person model from the struct
}
However, I can't get this to work, as I'm getting errors related to how the PersonModel
does not implement the Model
interface.
My main goal is to have a unified interface for all models in my application (implementing create
and update
) that can be used by the controllers. How would I go about overcoming this problem?
You should try to implement your method like this, it's just because you ask in your func Create and Update an empty interface as params :
func (model *PersonModel) Create(v interface{}) (int64, error) {
// do database related stuff to create the person from the struct
}
func (model *PersonModel) Update(id string, v interface{}) (error) {
// do database related stuff to update the person model from the struct
}