github.com/wtfutil/wtf@v0.43.0/modules/urlcheck/client.go (about) 1 package urlcheck 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "net/http" 8 "time" 9 10 "github.com/wtfutil/wtf/logger" 11 ) 12 13 // Perform the requet of the header for a given URL 14 func DoRequest(urlRequest string, timeout time.Duration, client *http.Client) (int, string) { 15 16 // Define a Context with the timeout for the request 17 ctx, cancel := context.WithTimeout(context.Background(), timeout) 18 defer cancel() 19 20 // Request 21 req, err := http.NewRequest(http.MethodHead, urlRequest, nil) 22 if err != nil { 23 logger.Log(fmt.Sprintf("[urlcheck] ERROR %s: %s", urlRequest, err.Error())) 24 return InvalidResultCode, "New Request Error" 25 } 26 req = req.WithContext(ctx) 27 28 // Send the request 29 res, err := client.Do(req) 30 if err != nil { 31 if errors.Is(err, context.DeadlineExceeded) { 32 status := "Timeout" 33 logger.Log(fmt.Sprintf("[urlcheck] %s: %s", urlRequest, status)) 34 return InvalidResultCode, status 35 } 36 logger.Log(fmt.Sprintf("[urlcheck] %s: %s", urlRequest, err.Error())) 37 return InvalidResultCode, "Error" 38 } 39 40 defer res.Body.Close() 41 42 return res.StatusCode, res.Status 43 }