I'm trying to create view that will handle all basic CRUD operations on my gorm models. The goal is to pass model to the view and let all the magic happen.
I found topics about using reflections, so I did, but also read that is not "golang way".
The first problem that I head with this is gorm using always "value" table. So temporary solution for that is to force using "users" table or table name from CommonView
package controllers
import (
"encoding/json"
"fmt"
"github.com/jinzhu/gorm"
"net/http"
"reflect"
)
type CommonView struct {
db *gorm.DB
modelType reflect.Type
model interface{}
tableName string
}
func NewCommonView(db *gorm.DB, model interface{}, tableName string) *CommonView {
return &CommonView{
db: db,
modelType: reflect.TypeOf(model),
model: model,
tableName: tableName,
}
}
func (cv *CommonView) HandleList(w http.ResponseWriter, r *http.Request) {
modelSliceReflect := reflect.SliceOf(cv.modelType)
models := reflect.MakeSlice(modelSliceReflect, 0, 10)
fmt.Println(modelSliceReflect)
fmt.Println(models)
//modelsDirect := reflect.MakeSlice(reflect.TypeOf(cv.model), 0, 0)
cv.db.Table("users").Find(&models)
fmt.Println("From db: ")
fmt.Println(models)
modelType := reflect.TypeOf(modelSliceReflect)
fmt.Println("Type name: " + modelType.String())
modelsJson, _ := json.Marshal(models)
fmt.Fprint(w, string(modelsJson))
}
Model: package models
import "golang.org/x/crypto/bcrypt"
type User struct {
Id string `json:"id" gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email string `json:"email" gorm:"unique;not null"`
Password string `json:"-"`
}
func (User) TableName() string {
return "user"
}
Gorm finding the rows in DB (know that from gorm log). But json don't dump them - guess it's in wrong type and can't handle that. Any ideas how do handle this problem?
If you also have any other solutions how to solve problem of CRUD view, I will be also very grateful.