Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang:无法连接MongoDB_Mongodb_Go - Fatal编程技术网

Golang:无法连接MongoDB

Golang:无法连接MongoDB,mongodb,go,Mongodb,Go,我正在尝试在使用运行数据库时将Go应用程序连接到MongoDB服务器 我能够使用shell连接到DB并执行不同的操作。但是,Go应用程序在连接到DB时失败。我正在使用下面的代码,我试图实现一个可供所有路由使用的db中间件: 中间件代码: package db import ( "net/http" "os" "github.com/gorilla/context" "github.com/urfave/negroni" mgo "gopkg.in/mg

我正在尝试在使用运行数据库时将Go应用程序连接到MongoDB服务器

我能够使用shell连接到DB并执行不同的操作。但是,Go应用程序在连接到DB时失败。我正在使用下面的代码,我试图实现一个可供所有路由使用的db中间件:

中间件代码:

package db

import (
    "net/http"
    "os"

    "github.com/gorilla/context"
    "github.com/urfave/negroni"
    mgo "gopkg.in/mgo.v2"
)

const key = "dbkey"

func GetDb(r *http.Request) *mgo.Database {
    if rv := context.Get(r, key); rv != nil {
        return rv.(*mgo.Database)
    }
    return nil
}

func SetDb(r *http.Request, val *mgo.Database) {
    context.Set(r, key, val)
}

func MongoMiddleware() negroni.HandlerFunc {
    database := os.Getenv("DB_NAME")
    session, err := mgo.Dial("127.0.0.1:27017")

    if err != nil {
        println(err) // error message below
    }

    return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
        reqSession := session.Clone()
        defer reqSession.Close()
        db := reqSession.DB(database)
        SetDb(r, db)
        next(rw, r)
    })
}
我得到的错误是:

panic: runtime error: invalid memory address or nil pointer dereference
路线和主包代码:

package main

import (
    gmux "github.com/gorilla/mux"
    "github.com/urfave/negroni"
    "github.com/mypro/db"
    "github.com/mypro/hub"
)

func main() {
    router := gmux.NewRouter()

    router.HandleFunc("/name", hub.Create).
        Methods("GET")

    n := negroni.Classic()
    n.Use(db.MongoMiddleware())
    n.UseHandler(router)
    n.Run(":9000")
}
使用db中间件查找集合的方法:

type Name struct {
    Id   bson.ObjectId `bson:"_id"`
    Name string        `bson:"name"`
}

func Create(w http.ResponseWriter, r *http.Request) {
    var aName Name
    db := db.GetDb(r)
    names := db.C("x")

    err := names.Find(bson.M{"name": "sam"}).One(&aName)
    if err != nil {
        log.Print(err)
    }
    fmt.Println(&aName)
    json.NewEncoder(w).Encode(&aName)
}

给我们更多的背景。这不是一个会被发现的错误。您正在使用无效的内存地址或nil指针解引用。我添加了更多上下文。我发现可能出现错误的唯一地方是在检查nil之前,在
Create
方法中使用
db
var。供将来参考-在请求上下文中传递db连接不是一个好做法。”这是我为更好的方法给出的一个简单示例。您是正确的db为nil,但我不知道为什么GetDb返回nil。这是调试器非常好的地方。设置前在
SetDb
中检查
val
,获取后在
GetDb
中检查
rv
;这可能会让你对正在发生的事情有所了解。