Golang数据库管理器API概念,错误与类型断言 [英] Golang database manager api concept, error with type assertion
问题描述
创建数据库管理器API的基本概念,用于通过API获取数据。我正在使用GORM来获取这些strcuts实例的数据。所以有300-400代表表格的结构。
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
}
下一步我实现了一个函数,该函数通过表名返回结构的正确实例,我通过API端点参数获得。
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
}
有一个操作结构,其中唯一的一个字段是数据库。有一些方法,例如我想使用GORM db.Last(&用户)函数的GetLast()。
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)
}
解决方案工作,但在这种情况下,我失去了模块化。我尝试使用 reflect.TypeOf(modelStruct)
,但它也不起作用,因为reflect.TypeOf的结果是一个reflect.Type,它不是golang类型。
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.
推荐答案
基本上,我解决了这个问题,将模型作为指针,并在将其作为json文件返回之后解决。
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),
}
它通过表格类型返回一个新模型。我可以使用gorm First()函数。然后json将它统一起来,然后返回。
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)
}
清除模型指针,因为First()函数存储最新查询的回调函数。
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()))
}
这篇关于Golang数据库管理器API概念,错误与类型断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!