我正在嘗試創建視圖來處理我的 gorm 模型上的所有基本 CRUD 操作。目標是將模型傳遞給視圖并讓所有的魔法發生。我找到了關于使用反射的主題,所以我做了,但也讀到那不是“golang 方式”。我遇到的第一個問題是總是使用“值”表的 gorm。因此,臨時解決方案是強制使用“用戶”表或表名CommonViewpackage controllersimport ( "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))}型號:包款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 在 DB 中查找行(從 gorm 日志中知道)。但是 json 不會轉儲它們 - 猜測它的類型錯誤并且無法處理。任何想法如何處理這個問題?如果您還有任何其他解決方案如何解決CRUD視圖的問題,我也將非常感謝。
1 回答

莫回無
TA貢獻1865條經驗 獲得超7個贊
問題源于 json 包處理reflect.Value
不符合預期的事實。
正如您在以下代碼片段中看到的,reflect.MakeSlice
返回一個類型Value
,而不是一個切片。
slice_empty_reflect_make := reflect.MakeSlice(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? reflect.SliceOf(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? reflect.TypeOf(5)),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 10, 10)
fmt.Printf("Type of reflect.MakeSlice(): %s\n",
? ? ? ? ? ?reflect.TypeOf(slice_empty_reflect_make).Name())
這產生:
Type of reflect.MakeSlice(): Value
當您在 json 編組器中輸入時Value,它將返回一個對象,而不是數組:
Json: {}
Error: <nil>
Value您需要使用以下命令返回到界面.Interface():
jsonBytes, err := json.Marshal(slice_empty_reflect_make.Interface())
- 1 回答
- 0 關注
- 192 瀏覽
添加回答
舉報
0/150
提交
取消