我刚刚在 youtube( https://youtu.be/GwQ1hvuSNJA ) 上遵循了本教程。
但是在 go run main.go
之后我收到错误“noreachableservers”
我怎样才能弄清楚?我应该将 localhost 更改为 mongodb uri 吗?
下面是源代码。
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)
}
}()
}
最佳答案
附注:github.com/globalsign/mgo
早已无人维护(已经四年多了)。请使用 official MongoDB Go driver .
您可以将 MongoDB URI 传递给 mgo.Dial()
,不仅仅是主机名。您未指定的部分将使用与您的实际值不匹配的默认值。因此请提供完整的 URI。
它的语法为:
[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.
所以这样做:
uri := fmt.Sprintf("mongodb://%s:%s/%s", hostName, port, dbName)
sess, err := mgo.Dial(uri)
关于MongoDB 与 golang 错误 "no reachable servers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73541056/