github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/health/checks/ping_check.go (about) 1 package checks 2 3 import ( 4 "fmt" 5 "io" 6 "net/http" 7 "time" 8 ) 9 10 type PingCheck struct { 11 URL string 12 Method string 13 Timeout int 14 client http.Client 15 Body io.Reader 16 Headers map[string]string 17 Error error 18 } 19 20 func CheckPingStatus(URL, Method string, Timeout int, Body io.Reader, Headers map[string]string) error { 21 check := NewPingCheck(URL, Method, Timeout, Body, Headers) 22 return check.checkstatus() 23 } 24 25 func NewPingCheck(URL, Method string, Timeout int, Body io.Reader, Headers map[string]string) PingCheck { 26 if Method == "" { 27 Method = "GET" 28 } 29 30 if Timeout == 0 { 31 Timeout = 500 32 } 33 34 pingCheck := PingCheck{ 35 URL: URL, 36 Method: Method, 37 Timeout: Timeout, 38 Body: Body, 39 Headers: Headers, 40 Error: nil, 41 } 42 pingCheck.client = http.Client{ 43 Timeout: time.Duration(Timeout) * time.Millisecond, 44 } 45 46 return pingCheck 47 } 48 49 func (p PingCheck) checkstatus() error { 50 51 defer func() { 52 if r := recover(); r != nil { 53 return 54 } 55 }() 56 57 req, err := http.NewRequest(p.Method, p.URL, p.Body) 58 59 if err != nil { 60 p.Error = fmt.Errorf("Error creating request: %s", err) 61 return fmt.Errorf("Error creating request: %s", err) 62 } 63 64 for key, value := range p.Headers { 65 req.Header.Add(key, value) 66 } 67 resp, err := p.client.Do(req) 68 if err != nil { 69 p.Error = fmt.Errorf("Error sending request: %s", err) 70 return p.Error 71 } 72 resp.Body.Close() 73 if resp.StatusCode >= 300 { 74 p.Error = fmt.Errorf("Error response status code: %d", resp.StatusCode) 75 return p.Error 76 } 77 return nil 78 } 79 80 func (p PingCheck) Name() string { 81 return "ping-" + p.URL 82 }