首页 文章

Golang数据库管理器api概念,类型断言错误

提问于
浏览
1

创建数据库管理器API以通过API获取数据的基本概念 . 我正在使用GORM来获取strcuts实例的数据 . 所以有300-400结构代表表 .

type Users struct {
  ID int64
  Name string
}

type Categories struct {
  ID int64
  Category string
}

下一步我实现一个函数,它通过表名返回结构的正确实例,我通过API endpoints 参数得到了什么 .

func GetModel(model string) interface{} {
  switch model {
  case "users":
    return Users{}
  case "categories"
    return Categories{}
  }
  return false
}

在有一个操作结构之后,只有一个字段是DB . 有方法,例如GetLast(),我想使用GORM db.Last(&users)函数 .

func (o Operations) GetLast(model string) interface{} {
  modelStruct := GetModel(model)
  .
  .
  .
  return o.DB.Last(&modelStruct)
}

有分,所以这是我不知道的 . 当前的解决方案不起作用,因为在这种情况下它是一个接口{}我需要做一个类型断言more info in this question . 类型断言看起来像:

func (o Operations) GetLast(model string) interface{} {
  modelStruct := GetModel(model)
  .
  test := modelStruct.(Users)
  .
  return o.DB.Last(&test)
}

这个解决方案有效,但在这种情况下我失去了模块化 . 我尝试使用 reflect.TypeOf(modelStruct) ,但它也无法正常工作,因为reflect.TypeOf的结果是一个reflect.Type,而不是golang类型 .

1 回答

  • 0

    基本上我解决了这个问题,将模型作为指针,然后将其作为json文件返回 .

    所以我的模型如下:

    var Models = map[string]interface{}{
        "users": new(Users),
        "categories": new(Categories),
    }
    

    它按表格类型返回一个新模型 . 我可以用于gorm First()函数 . 然后json Marshal吧,并返回 .

    func (o Operation) First(model string, query url.Values) string {
        modelStruct := Models[model]
        db := o.DB
        db.First(modelStruct)
        response, _ := json.Marshal(modelStruct)
        clear(modelStruct)
        return string(response)
    }
    

    在返回之前,我清除了模型指针,因为First()函数存储了最新查询的回调 .

    func clear(v interface{}) {
        p := reflect.ValueOf(v).Elem()
        p.Set(reflect.Zero(p.Type()))
    }
    

相关问题