dtmjl4427 2017-02-04 09:38
浏览 39
已采纳

Golang数据库管理器api概念,类型声明错误

The base concept creating a Database Manager API for getting data through an API. I am using the GORM for getting data of the instances of the strcuts. So there is 300-400 struct which represents the tables.

type Users struct {
  ID int64
  Name string
}

type Categories struct {
  ID int64
  Category string
}

The next step I implement a function which is return the correct instance of the struct by table name, what I get through the API endpoint param.

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

After there is an operations struct where the only one field is the DB. There is methods, for example the GetLast() where I want to use the GORM db.Last(&users) function.

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

There is points so this is what I don't know. The current solution is not working because in this case it is an interface{} I need make a type assertion more info in this question. The type assertion is looks like:

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

This solution working, but in this case I lost the modularity. I try using the reflect.TypeOf(modelStruct), but it is also not working because the result of the reflect.TypeOf is a reflect.Type, with is not a golang type.

  • 写回答

1条回答 默认 最新

  • duanhe0817825 2017-02-10 17:33
    关注

    Basically I solved the problem, for getting the model as a pointer, and after I return it back as a json file.

    So my model is the following:

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

    And it is return back a new model by table type. what I can use for gorm First() function. Then json Marshal it, and return.

    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)
    }
    

    Before the return I clear the model pointer because the First() function store callbacks for the latest queries.

    func clear(v interface{}) {
        p := reflect.ValueOf(v).Elem()
        p.Set(reflect.Zero(p.Type()))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集