mongodbgomgo

MongoDB error "no reachable servers" with golang


I just followed this tutorial on youtube(https://youtu.be/GwQ1hvuSNJA). But I got an error "no reachable servers" after go run main.go How can I figure it out? Should I change localhost to mongodb uri? Below is source code.

var rnd *renderer.Render
var db *mgo.Database

const (
    hostName       string = "localhost"
    dbName         string = "demo_todo"
    collectionName string = "todo"
    port           string = ":3000"
)

func init() {
    rnd = renderer.New()
    sess, err := mgo.Dial(hostName)
    checkErr(err)
    sess.SetMode(mgo.Monotonic, true)
    db = sess.DB(dbName)
}

func main() {
    stopChan := make(chan os.Signal, 1)
    signal.Notify(stopChan, os.Interrupt)

    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Get("/", homeHandler)

    r.Mount("/todo", todoHandlers())

    srv := &http.Server{
        Addr:         port,
        Handler:      r,
        ReadTimeout:  60 * time.Second,
        WriteTimeout: 60 * time.Second,
        IdleTimeout:  60 * time.Second,
    }

    go func() {
        log.Println("Listening on port ", port)
        if err := srv.ListenAndServe(); err != nil {
            log.Printf("listen: %s\n", err)
        }
    }()
}


Solution

  • As a side note: github.com/globalsign/mgo has long gone unmaintained (over 4 years now). Do use the official MongoDB Go driver.


    You may pass a MongoDB URI to mgo.Dial(), not just a host name. Parts you don't specify will use a default which doesn't match your actual values. So provide a full URI.

    It has the syntax of:

    [mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options]
    

    For example, it may be as simple as:

    localhost
    

    Or more involved like:

    mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb
    

    If the port number is not provided for a server, it defaults to 27017.

    The username and password provided in the URL will be used to authenticate into the database named after the slash at the end of the host names, or into the "admin" database if none is provided. The authentication information will persist in sessions obtained through the New method as well.

    So do it like this:

    uri := fmt.Sprintf("mongodb://%s:%s/%s", hostName, port, dbName)
    sess, err := mgo.Dial(uri)