Priyanka
Priyanka

Reputation: 364

GOLANG check whether mongodb is running

I am writing a GO script to check whether Mongo server is running. My code is as,

import "bytes"
import "os/exec"
import "fmt"

func main() {
    cmd := exec.Command("ps", "-ef", "|", "grep", "mongod", "|", "grep", "-v", "grep", "|", "wc", "-l", "|", "tr", "-d", "'", "'")

    fmt.Println(cmd)
    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
    }
    fmt.Println("Result: " + out.String())
}

But Getting Error as , "exit status 1: error: garbage option" . Is there other way to check this with GOLANG? Please let me know.

Upvotes: 0

Views: 3637

Answers (1)

Adrian
Adrian

Reputation: 46433

If you want to go beyond porting a bash script to Go (which is often more trouble than it's worth), you can use the mgo library to actually connect to a MongoDB instance and check if it is healthy:

package main

import (
    "gopkg.in/mgo.v2"
    "fmt"
    "os"
)

func main() {
    sess, err := mgo.Dial("localhost")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer sess.Close()
    err = sess.Ping()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println("MongoDB server is healthy.")
    os.Exit(0)
}

Upvotes: 2

Related Questions