Go O & M to check the web service status
Continue the previous code. You often need to check the status of web services during O & M. You can set a test page on the web (you can query the database and return a specified value)
Package main // package import ("flag" "fmt" "io/ioutil" "log" "net" "net/http" "regexp ") // define the script VERSION const VERSION = "0.1.0" // use flag to define the command input parameter var Input_protocol = flag. string ("p", "tcp", "The protocol you want to check") // defines The script used to Detect tcp services. The net package func tcp (url string) is used) int {_, err: = net. dial ("tcp", url) if err! = Nil {fmt. println (err) return 0} else {return 1} // defines the script for detecting the udp Service, and uses the net Package func udp (url string) int {_, err: = net. dial ("udp", url) if err! = Nil {fmt. println (err) return 0} else {return 1} // defines the http service detection script. 1 is returned for success, and 0 func chttp (url, checkword string) is returned for failure) int {res, err: = http. get (url) if err! = Nil {// returns an error log if the connection fails. fatal (err) return 0} // read the response robots, err: = ioutil. readAll (res. body) // closes the resource res. body. close () // cause of failure returned if err! = Nil {log. Fatal (err) return 0} // call the regexp function to find the checkword word, err: = regexp. MatchString (checkword, string (robots) if err! = Nil {log. println (err) return 0} if word {log. printf ("The '% s' find in' % S'", checkword, url) return 1} log. printf ("The '% s' not find in' % S'", checkword, url) return 0} func main () {flag. parse () if flag. NArg () <1 {useage: = "Example: check-p tcp 192.168.7.26: 22 or check-p udp 192.168.7.23: 123 or check-p http http://dockerpool.com dockerpool" fmt. println (useage) return} p: = * Input_protocol switch {case p = "tcp": r: = tcp (flag. args () [0]) fmt. println (r) case p = "udp": r: = udp (flag. args () [0]) fmt. println (r) case p = "http": chttp (flag. args () [0], flag. args () [1])}
Example:
$ check -p http http://dockerpool.com dockerpool2015/01/08 10:38:53 The `dockerpool` find in `http://dockerpool.com`$ check -p tcp www.sina.com:801$ check -p tcp www.sina.com:88dial tcp 61.172.201.20:88: connection refused0