-
-
Save acoshift/ba30cd12b75d7b8e26eae43db5a8bda3 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"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