dongwh1992 2019-01-07 14:01
浏览 61
已采纳

在golang中通用处理CRUD动作

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.

  • 写回答

1条回答 默认 最新

  • doubi1713 2019-01-07 15:56
    关注

    The problem rises from the fact that the json package handles reflect.Value not as expected. You can find a similar discussion here: https://github.com/golang/go/issues/7846

    As you can see in the following code snippet, reflect.MakeSlice returns a type Value, not a slice.

    slice_empty_reflect_make := reflect.MakeSlice(
                                        reflect.SliceOf(
                                                reflect.TypeOf(5)),
                                        10, 10)
    
    fmt.Printf("Type of reflect.MakeSlice(): %s
    ",
               reflect.TypeOf(slice_empty_reflect_make).Name())
    

    This yields:

    Type of reflect.MakeSlice(): Value
    

    When you feed the Value in the json marshaller, it will return an object, not an array:

    Json: {}
    Error: <nil>
    

    You need to get back to the interface of the Value by using .Interface():

    jsonBytes, err := json.Marshal(slice_empty_reflect_make.Interface())
    

    And this is a duplicate in disguise of How do I serialize a map of type [string]reflect.Value?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了