Golang MongoDB错误:结果参数必须是切片地址

时间:2016-06-25 23:28:03

标签: mongodb rest go mgo

我有一个函数需要从mongoDB集合中检索所有用户,当我尝试通过REST端点调用它时会抛出错误。功能是:

func (usercontroller UserController) GetAllUsers(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
        session := usercontroller.session.Copy()
        defer session.Close()

        // Stub user
        result := models.User{}

        // get all users
        if err := session.DB("Auth").C("users").Find(nil).All(&result); err != nil {
                w.WriteHeader(404)
                return
        }

        // Marshal provided interface into JSON structure
        mResult, _ := json.Marshal(result)

        // Write content-type, statuscode, and the data package
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(200)
        fmt.Fprintf(w, "%s", mResult)
}

错误是:

2016/06/25 16:00:21 http: panic serving 127.0.0.1:49898: result argument must be a slice address
goroutine 13 [running]:
net/http.(*conn).serve.func1(0xc82005e380)
    /usr/lib/go-1.6/src/net/http/server.go:1389 +0xc1
panic(0x729b60, 0xc82000ba50)
    /usr/lib/go-1.6/src/runtime/panic.go:443 +0x4e9
gopkg.in/mgo%2ev2.(*Iter).All(0xc8201280f0, 0x704600, 0xc82007e360, 0x0, 0x0)
    /root/work/src/gopkg.in/mgo.v2/session.go:3696 +0x742
gopkg.in/mgo%2ev2.(*Query).All(0xc8200bc600, 0x704600, 0xc82007e360, 0x0, 0x0)
    /root/work/src/gopkg.in/mgo.v2/session.go:3723 +0x4f
Auth-REST-Server/controllers.UserController.GetAllUsers(0xc82000d040, 0x7f3c1b9bf950, 0xc820061c70, 0xc8200c6380, 0x0, 0x0, 0x0)
    /root/work/src/Auth-REST-Server/controllers/user.go:34 +0x251
Auth-REST-Server/controllers.(UserController).GetAllUsers-fm(0x7f3c1b9bf950, 0xc820061c70, 0xc8200c6380, 0x0, 0x0, 0x0)
    /root/work/src/Auth-REST-Server/server.go:21 +0x5f
github.com/julienschmidt/httprouter.(*Router).ServeHTTP(0xc820016380, 0x7f3c1b9bf950, 0xc820061c70, 0xc8200c6380)
    /root/work/src/github.com/julienschmidt/httprouter/router.go:344 +0x195
net/http.serverHandler.ServeHTTP(0xc820122000, 0x7f3c1b9bf950, 0xc820061c70, 0xc8200c6380)
    /usr/lib/go-1.6/src/net/http/server.go:2081 +0x19e
net/http.(*conn).serve(0xc82005e380)
    /usr/lib/go-1.6/src/net/http/server.go:1472 +0xf2e
created by net/http.(*Server).Serve
    /usr/lib/go-1.6/src/net/http/server.go:2137 +0x44e

我在这里做错了什么。我以为我可以调用Find(nil).All(& result)并相应地检索所有记录。

1 个答案:

答案 0 :(得分:6)

在您的代码中,您有:

// Stub user
result := models.User{}

因此,结果代表单个用户,但您希望数据库中的所有用户都这样做,所以以下内容应该完成这项任务:

// Stub user
result := make([]models.User, 0, 10) // Here you can specify a len and a cap.

这样,结果就是一片模型。用户。

此外,在Golang中,您永远不应忽略错误:

// Marshal provided interface into JSON structure
mResult, _ := json.Marshal(result)

应该是:

// Marshal provided interface into JSON structure
mResult, err := json.Marshal(result)
if err != nil {
    // do something with the error (log it or write it in the response)
}

编辑:我更新了代码,对不起。