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
1 Answer 1
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.
-
1\$\begingroup\$ Please review the OP when proposing an alternative solution. \$\endgroup\$dfhwze– dfhwze2019年06月21日 19:30:56 +00:00Commented Jun 21, 2019 at 19:30