doufeiqiong3515 2017-07-14 13:57
浏览 151

Golang:无法与MongoDB连接

I am trying to connect Go application with MongoDB server while running the database using docker.

I'm able to connect to the DB using the shell and perform different actions. However, the Go app fails when connecting to the DB. I'm using mgo driver and below is the code in use where am trying to implement a db middleware that can be used by all routes:

middleware code:

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)
    })
}

the error am getting is :

panic: runtime error: invalid memory address or nil pointer dereference

route and main package code:

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")
}

method that consume the db middleware to find a collection:

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)
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 划分vlan后不通了
    • ¥15 GDI处理通道视频时总是带有白色锯齿
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)
    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 Revit2020下载问题
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大