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