Help Center/
GeminiDB/
GeminiDB Mongo API/
Best Practices/
Connecting to an Instance Using Golang/
Connecting to a Database
Updated on 2024-02-07 GMT+08:00
Connecting to a Database
Prerequisites
- To connect an ECS to an instance, the ECS must be able to communicate with the GeminiDB Mongo instance. You can run the following command to connect to the IP address and port of the instance server to test the network connectivity.
curl ip:port
If the message It looks like you are trying to access MongoDB over HTTP on the native driver port is displayed, the ECS and GeminiDB Mongo instance can communicate with each other.
- If SSL is enabled, download the root certificate and upload it to the ECS.
Connection Code
- Enabling SSL
//Construct an authentication credential. // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables. // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed. username = System.getenv("EXAMPLE_USERNAME_ENV") password = System.getenv("EXAMPLE_PASSWORD_ENV") credential := options.Credential{ AuthMechanism: "SCRAM-SHA-1", AuthSource: "admin", Username: username, Password: password, } //HA URI. Note that SetDirect is set to false. highProxyUri := "mongodb://host1:8635,host2:8635/?ssl=true" clientOpts := options.Client().ApplyURI(highProxyUri) clientOpts = clientOpts.SetTLSConfig(&tls.Config { InsecureSkipVerify: true, }).SetDirect(false).SetAuth(credential) //URI of the direct connection. Note that SetDirect is set to true. //directUri := "mongodb://host:8635/?ssl=true" //clientOpts := options.Client().ApplyURI(highProxyUri) //clientOpts = clientOpts.SetTLSConfig(&tls.Config { // InsecureSkipVerify: true, //}).SetDirect(true).SetAuth(credential) // Connect to an instance. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() client, err := mongo.Connect(ctx, clientOpts) if err != nil { fmt.Println("Failed to connect to the mongo instance:", err) return } //Ping the primary node. ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) defer cancel()err = client.Ping(ctx, readpref.Primary()) if err != nil {fmt.Println ("Failed to ping the primary node: ",err) return } //Select a database and collection. collection := client.Database("test").Collection("numbers") //Insert a record. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) defer cancel() oneRes, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}}) if err != nil{fmt.Println("Failed to insert a record: ",err) return }else { fmt.Println(oneRes) } Import {0} records in batches. ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second) defer cancel() docs := make([]interface{}, 100) for i := 0; i < 100; i++{ docs[i] = bson.D{{"name", "name"+strconv.Itoa(i)}, {"value", i}} } manyRes, err := collection.InsertMany(ctx, docs) if err != nil { fmt.Println("Batch insertion failed: ",err) return }else { fmt.Println(manyRes) }
- Disabling SSL
//HA connection. The value of readPreference is primary (by default), indicating that the primary node is read-only. The value primaryPreferred indicates that the primary node is preferred. If the primary node is unavailable, the secondary node is read. // Secondary: read-only node. If the secondary node is unavailable, an error is reported. secondaryPreferred: The secondary node is preferred. If the secondary node is unavailable, the primary node is read. // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables. // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed. username = System.getenv("EXAMPLE_USERNAME_ENV") password = System.getenv("EXAMPLE_PASSWORD_ENV") highProxyUri := fmt.Sprintf("mongodb://%v:%v@host1:8635,host2:8635/?authSource=admin&replicaSet=replica&readPreference=secondaryPreferred",username,password) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() clientOpts := options.Client().ApplyURI(highProxyUri) client, err := mongo.Connect(ctx, clientOpts) //Ping the primary node. ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) defer cancel()err = client.Ping(ctx, readpref.Primary()) if err != nil { fmt.Println("Failed to ping the primary node: ",err) return } //Select a database and collection. collection := client.Database("test").Collection("numbers") //Insert a record. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) defer cancel() res, err := collection.InsertOne(ctx, bson.D{{"name", "e"}, {"value", 2.718}}) if err != nil{ fmt.Println("Failed to insert a record: ",err) return }else { fmt.Println(res) }
Parent topic: Connecting to an Instance Using Golang
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
The system is busy. Please try again later.
For any further questions, feel free to contact us through the chatbot.
Chatbot