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)
}
}()
}
As a side note:
github.com/globalsign/mgohas 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:
So do it like this: