1
\$\begingroup\$

I have written a program in golang which checks the mongodb is running or not using commands. But I'm not sure that the program is sufficient or there is something that needs to change in the program. Can you review my code so I can be sure that my code does not have any error or doesn't break if there is any problem at all?

Code

package main
import (
 "bytes"
 "fmt"
 "os/exec"
)
/*
*Function check mongodb is running? if not running then it will help to run it by command
*/
func main() {
 status := ExecuteCommand("systemctl is-active mongod")
 if status == true {
 fmt.Println("Connected")
 } else {
 fmt.Println("disconnected")
 status = ExecuteCommand("echo <password> | sudo -S service mongod start")
 if status == true {
 fmt.Println("Connected")
 }
 }
}
/*
* Function to execute the command using golang code.
*
* Params command type string
*
* Used by main func
*
* Returns nil (if no error)
* or err type error (if error occurs)
*/
func ExecuteCommand(command string) bool {
 cmd := exec.Command("sh", "-c", command)
 var out bytes.Buffer
 var stderr bytes.Buffer
 cmd.Stdout = &out
 cmd.Stderr = &stderr
 err := cmd.Run()
 if err != nil {
 fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
 return false
 }
 return true
}

Golang playground

dfhwze
14.1k3 gold badges40 silver badges101 bronze badges
asked Jan 30, 2019 at 12:46
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I think your code works. Another approach would be trying to connect to the database using the MongoDB Go Driver.

import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref")
func GetClient() *mongo.Client {
 clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
 client, err := mongo.NewClient(clientOptions)
 if err != nil {
 log.Fatal(err)
 }
 err = client.Connect(context.Background())
 if err != nil {
 log.Fatal(err)
 }
 return client
}

If you can't connect (assuming you passing the right information), it means that the database is not running.

But like I said, it's just another approach.

AlexV
7,3532 gold badges24 silver badges47 bronze badges
answered Jun 21, 2019 at 19:09
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please review the OP when proposing an alternative solution. \$\endgroup\$ Commented Jun 21, 2019 at 19:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.