英文:
GOLANG check whether mongodb is running
问题
我正在编写一个GO脚本来检查Mongo服务器是否正在运行。我的代码如下:
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())
}
但是出现错误,错误信息为"exit status 1: error: garbage option"。是否有其他方法可以使用GOLANG来检查Mongo服务器是否运行?请告诉我。
英文:
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.
答案1
得分: 2
如果你想超越将一个bash脚本移植到Go语言(这往往比它值得的麻烦多),你可以使用mgo库来实际连接到一个MongoDB实例并检查其是否健康:
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服务器正常运行。")
os.Exit(0)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论