Skip to content

Instantly share code, notes, and snippets.

@acoshift

acoshift/main.go Secret

Created July 6, 2017 19:59
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 acoshift/ba30cd12b75d7b8e26eae43db5a8bda3 to your computer and use it in GitHub Desktop.
Save acoshift/ba30cd12b75d7b8e26eae43db5a8bda3 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
func main() {
http.HandleFunc("/", checkSite)
http.ListenAndServe(":8080", nil)
}
func checkSite(w http.ResponseWriter, r *http.Request) {
q := r.RequestURI[1:]
req, err := http.NewRequest(http.MethodGet, "http://"+q, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if urlErr, ok := err.(*url.Error); ok {
if urlErr.Err == context.Canceled {
log.Println("user cancel request")
return
}
if urlErr.Err == context.DeadlineExceeded {
fmt.Fprintf(w, "Site \"%s\" is down.", q)
return
}
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(w, "Site \"%s\" is down.", q)
return
}
fmt.Fprintf(w, "Site \"%s\" is up.", q)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment