我正在尝试为我的服务创建基本的CRUD。它基于在结构中创建的数据模型。问题是我真的不想为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"`
}

我想要做的是通用方法来检索给定模型的数组。使用模型对我来说很重要。我可以使用纯interface{}类型快速完成此操作,但会失去模型功能,例如在JSON输出中隐藏某些属性(例如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)
}
GetModelAGetModelB是路由处理程序,它使用通用方法GetBySlug返回由给定模型格式化的JSON。

我想做的只是给定模型的数组。到目前为止,我很难将结果转换为struct:
// 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参数设置为接口数组{}。另外,如果我尝试将结果强制转换为[]interface{}方法中的GetList(),我也不能将其强制转换为res参数,因为它不是数组。

有没有很好的方法可以做到这一点?也许我认为错了,应该重新设计方法吗?任何意见,将不胜感激。

最佳答案

您可以声明代表模型 slice 的新类型。例如,

type ModelAList []ModelA
type ModelBList []ModelB

然后,当您将这些新类型的变量传递到r.GetDocumentBySlug()中时,encoding/json包中的函数将相应地解组 slice 。

您可以找到工作示例here (marshaling)here (unmarshaling)

关于go - 检索模型(结构)列表的通用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45650875/

10-09 15:19
查看更多