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

在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?

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?