Go 检索模型(结构)列表的通用方法

Go 检索模型(结构)列表的通用方法,go,struct,crud,Go,Struct,Crud,我正在尝试为我的服务创建基本CRUD。它基于在structs中创建的数据模型。问题是我真的不想重复CRUD方法的代码。例如,我将ModelA和ModelB定义为结构: type ModelA struct { ID bson.ObjectId `json:"ID,omitempty" bson:"_id,omitempty"` Slug string `json:"slug" bson:"slug,om

我正在尝试为我的服务创建基本CRUD。它基于在structs中创建的数据模型。问题是我真的不想重复CRUD方法的代码。例如,我将ModelA和ModelB定义为结构:

type ModelA struct {
    ID              bson.ObjectId     `json:"ID,omitempty" bson:"_id,omitempty"`
    Slug            string            `json:"slug" bson:"slug,omitempty"`
    Creator         string            `json:"-" bson:"creator,omitempty"`
    DefaultLanguage string            `json:"defaultLanguage" bson:"defaultLanguage,omitempty"`
}

type ModelB struct {
    ID              bson.ObjectId     `json:"ID,omitempty" bson:"_id,omitempty"`
    Type            string            `json:"type" bson:"type,omitempty"`
}
我想要的是生成一个通用方法,它检索给定模型的数组。使用模型对我来说很重要。我可以用纯接口{}类型快速完成,但会失去模型功能,例如在JSON输出ex.ModelA.Creator中隐藏一些属性

到目前为止,我已经创建了用于创建新数据和检索单个模型的通用方法。下面是示例代码:

// GET: /modelsa/{:slug}
func (r *Routes) GetModelA(w rest.ResponseWriter, req *rest.Request) {
    // set model as ModelA
    var model models.ModelA
    r.GetBySlug(w, req, &model, "models")
}

// GET: /modelsb/{:slug}
func (r *Routes) GetModelB(w rest.ResponseWriter, req *rest.Request) {
    // set model as ModelB
    var model models.ModelB
    r.GetBySlug(w, req, &model, "models")
}

func (r *Routes) GetBySlug(w rest.ResponseWriter, req *rest.Request, m interface{}, collection string) {
    slug := req.PathParam("slug")

    if err := r.GetDocumentBySlug(slug, collection, m, w, req); err != nil {
        rest.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.WriteJson(m)
}
GetModelA和GetModelB是路由处理程序,使用通用方法GetBySlug返回给定模型格式化的JSON

我想做同样的事情,但是使用给定模型的数组。到目前为止,我在将结果强制转换到结构中时遇到了问题:

// GET /modelsa/
func (r *Routes) GetModels(w rest.ResponseWriter, req *rest.Request) {
    // I think in this case I don't have to pass an array of struct
    // because the given struct is only reference. It could be:
    // var result models.ModelA as well. Converting it into array could 
    // be done in GetList() method
    var result []models.ModelA
    r.GetList(w, req, &result, "models")
}

func (r *Routes) GetList(w rest.ResponseWriter, req *rest.Request, res interface{}, col string) {

}
我无法将res参数设置为接口{}的数组。另外,如果我尝试将结果强制转换为GetList方法内的[]接口{},则无法将其强制转换为res参数,因为它不是数组


有什么好办法吗?也许我认为不对,应该重新设计方法?如果您有任何建议,我们将不胜感激。

您可以声明代表您的模型的新类型。比如说,

type ModelAList []ModelA
type ModelBList []ModelB
然后,当您将这些新类型的变量传递到r.GetDocumentBySlug中时,encoding/json包中的函数将相应地解组切片


您可以找到工作示例和。

嗯,这是个好主意。没有考虑过创建新类型,但是如何将其传递给GetList方法?在我的示例中,存在类型为interface{}的res。我不能让它[]接口{},也不能检查结果的长度,因为它不是slice或arrayOk,它正在工作!我刚刚创建了接口{}类型,它保存给定的切片类型。删除并检查切片的长度。这样做不行。也许我得解开它。谢谢你的回答!!