Skip to content

Instantly share code, notes, and snippets.

@chrisfarms
Created August 22, 2011 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisfarms/1162117 to your computer and use it in GitHub Desktop.
Save chrisfarms/1162117 to your computer and use it in GitHub Desktop.
"ping" a site over HTTP every few seconds and check for status code 200 - just a little play in go
package main
import (
"fmt"
"http"
"time"
)
type Site struct {
url string
}
// do an HTTP get on the site's url
// check for a 200 status
// returns true if site is alive
func (s *Site) Check() bool {
client := &http.Client{}
r,err := client.Get(s.url)
if err != nil {
return false
}
return r.StatusCode == 200
}
// loop forever checking the site status
// every few seconds
func (s *Site) Monitor(ch chan *Site) {
for {
if !s.Check() {
ch <- s
}
time.Sleep(5*1e9)
}
}
// accept a slice of sites
// launch the Monitor goroutine and give it
// a channel to report errors to
// return the error-report channel
func MonitorAll(sites []*Site) chan *Site {
failures := make(chan *Site)
for i := range sites {
go sites[i].Monitor(failures)
}
return failures
}
// create a list of sites to check
// print a "failed" message if a site is unresponsive
func main() {
sites := make([]*Site,2)
sites[0] = &Site{"http://www.google.com"}
sites[1] = &Site{"http://localhost:5000"}
for site := range MonitorAll(sites) {
fmt.Println("Site is down", site.url)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment