Connecting to MongoDB Cloud Database in Go on Ubuntu
A developer recently encountered an issue while attempting to connect to a MongoDB Atlas database using Go on an Ubuntu system. The following code snippet was used for the connection:
func connectToDataBase() { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() client, err := mongo.Connect(ctx, options.Client().ApplyURI(dbURL)) if err != nil { log.Fatal("Error connecting to Database: ", err.Error()) } DB = client.Database("storyfactory") }
This code had previously worked on a Windows machine, but when executed on Ubuntu, it resulted in the error:
2019/04/13 00:20:37 Error connecting to Database: error parsing uri (mongodb+srv://User:[email protected]/test?retryWrites=true): lookup cluster0-gpxjk.gcp.mongodb.net on 127.0.0.53:53: cannot unmarshal DNS message exit status 1
Resolution
The error message "cannot unmarshal DNS message" is not specific to the MongoDB Go driver but rather an issue related to the way DNS messages are handled in Go version 1.11.x. Specifically, an update to the DNS message parsing logic in Go 1.11 introduced stricter compliance with RFC-2782, leading to errors with DNS responses that use domain name compression.
Workarounds
To resolve this issue, developers can implement the following workarounds:
Alternatively, developers can consider upgrading to a later version of Go (e.g., 1.12 or 1.13) where this issue has been addressed.
The above is the detailed content of Why Can\'t My Go Application Connect to MongoDB Atlas on Ubuntu, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!