github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/health/checks/signalRserver.go (about) 1 package checks 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "net/http" 9 10 "github.com/gorilla/websocket" 11 ) 12 13 type SignalRSrvCheck struct { 14 Ctx context.Context 15 WcAddress string 16 ServerAddress string 17 Error error 18 } 19 20 func NewSignalRSrvCheck(ctx context.Context, address string, wcaddress string) SignalRSrvCheck { 21 return SignalRSrvCheck{ 22 Ctx: ctx, 23 WcAddress: wcaddress, 24 ServerAddress: address, 25 Error: nil, 26 } 27 } 28 29 func CheckSignalRSrvStatus(ctx context.Context, address string, wcaddress string) error { 30 check := NewSignalRSrvCheck(ctx, address, wcaddress) 31 return check.CheckStatus() 32 } 33 34 func CheckSignalRSrvHttpStatus(ctx context.Context, address string, wcaddress string) error { 35 check := NewSignalRSrvCheck(ctx, address, wcaddress) 36 return check.CheckhttpStatus() 37 } 38 39 func (check SignalRSrvCheck) CheckStatus() error { 40 41 var checkErr error 42 checkErr = nil 43 go func() { 44 defer func() { 45 if r := recover(); r != nil { 46 return 47 } 48 }() 49 50 ticker := time.NewTicker(5 * time.Second) 51 for range ticker.C { 52 53 conn, _, err := websocket.DefaultDialer.Dial(check.WcAddress, nil) 54 if err != nil { 55 checkErr = fmt.Errorf("websocket connection failed: %w", err) 56 check.Error = checkErr 57 } 58 defer conn.Close() 59 } 60 }() 61 return checkErr 62 } 63 64 func (check SignalRSrvCheck) CheckhttpStatus() error { 65 66 var checkErr error 67 checkErr = nil 68 go func() { 69 defer func() { 70 if r := recover(); r != nil { 71 return 72 } 73 }() 74 75 ticker := time.NewTicker(5 * time.Second) 76 for range ticker.C { 77 resp, err := http.Get(check.ServerAddress) 78 if err != nil { 79 checkErr = fmt.Errorf("http connection failed: %w", err) 80 check.Error = checkErr 81 } 82 defer resp.Body.Close() 83 84 if resp.StatusCode == http.StatusOK { 85 checkErr = nil 86 } else { 87 checkErr = fmt.Errorf("SignalR server returned a non-OK status:", resp.Status) 88 check.Error = checkErr 89 } 90 } 91 }() 92 return checkErr 93 }