Created
May 8, 2018 01:51
-
-
Save wcharczuk/1f8a261c9f25e95841880731c92b89ef to your computer and use it in GitHub Desktop.
A very simple healthcheck loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"net/url" | |
"os" | |
"time" | |
) | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Fprintf(os.Stderr, "please supply a url to check") | |
os.Exit(1) | |
} | |
checkURL := os.Args[1] | |
var check *url.URL | |
var err error | |
check, err = url.ParseRequestURI(checkURL) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "err") | |
os.Exit(1) | |
} | |
var req *http.Request | |
req, err = http.NewRequest("GET", check.String(), nil) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "err") | |
os.Exit(1) | |
} | |
client := &http.Client{ | |
Timeout: 5 * time.Second, | |
Transport: &http.Transport{ | |
IdleConnTimeout: 30 * time.Second, | |
ResponseHeaderTimeout: 5 * time.Second, | |
}, | |
} | |
tick := time.Tick(10 * time.Second) | |
var res *http.Response | |
var start time.Time | |
var now string | |
var contentLength int64 | |
for { | |
select { | |
case <-tick: | |
start = time.Now() | |
res, err = client.Do(req) | |
now = time.Now().UTC().Format(time.RFC3339) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "%s %s %+v (%v)\n", now, check.String(), err, time.Since(start)) | |
continue | |
} | |
defer res.Body.Close() | |
contentLength, err = io.Copy(ioutil.Discard, res.Body) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "%s %s %+v (%v)\n", now, check.String(), err, time.Since(start)) | |
continue | |
} | |
if res.StatusCode > 299 { | |
fmt.Fprintf(os.Stderr, "%s %s status code: %v (%v)\n", now, check.String(), res.StatusCode, time.Since(start)) | |
continue | |
} | |
fmt.Fprintf(os.Stdout, "%s %s %v (%v)\n", now, check.String(), contentLength, time.Since(start)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment