sql >> Base de Datos >  >> NoSQL >> MongoDB

Golang / MGO -- pánico:no hay servidores accesibles

Ejecute la siguiente versión de su código publicado. Intente no modificar el código, al menos no cambie la posición de los números de línea. De esa manera, si publica un seguimiento de pila, los números coincidirán.

package main

import (
    "fmt"
    "time"
)

import (
    "labix.org/v2/mgo"
)

func connectToMongo() bool {
    ret := false
    fmt.Println("enter main - connecting to mongo")

    // tried doing this - doesn't work as intended
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Detected panic")
            var ok bool
            err, ok := r.(error)
            if !ok {
                fmt.Printf("pkg:  %v,  error: %s", r, err)
            }
        }
    }()

    maxWait := time.Duration(5 * time.Second)
    session, sessionErr := mgo.DialWithTimeout("localhost:27017", maxWait)
    if sessionErr == nil {
        session.SetMode(mgo.Monotonic, true)
        coll := session.DB("MyDB").C("MyCollection")
        if ( coll != nil ) {
            fmt.Println("Got a collection object")
            ret = true
        }
    } else { // never gets here
        fmt.Println("Unable to connect to local mongo instance!")
    }
    return ret
}

func main() {
    if ( connectToMongo() ) {
        fmt.Println("Connected")
    } else {
        fmt.Println("Not Connected")
    }
}

Cuando MongoDB está activo, veo:

enter main - connecting to mongo
Got a collection object
Connected

Cuando MongoDB está inactivo, veo:

enter main - connecting to mongo
Unable to connect to local mongo instance!
Not Connected

Si no ve el mismo comportamiento, publique el resultado, incluido el pánico que ve.