feat: refactor signal handling and update websocket disconnect handling

- remove os signal handling interrupt
- rename WaitForDisconnect to Disconnect function
- improve websocket disconnection logic
- exit keyboard listener on disconnect

🤖
This commit is contained in:
Sebastian Mark 2024-10-23 19:04:52 +02:00
parent deff8f3554
commit e14492a01c
2 changed files with 40 additions and 45 deletions

View file

@ -3,8 +3,6 @@ package client
import (
"atomicgo.dev/cursor"
"flag"
"os"
"os/signal"
"git.smsvc.net/pomodoro/ChronoTomato/internal/helper"
"git.smsvc.net/pomodoro/ChronoTomato/internal/shared"
@ -15,11 +13,7 @@ import (
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
var interrupt = make(chan os.Signal, 1)
func Start() {
signal.Notify(interrupt, os.Interrupt)
cursor.Hide()
defer cursor.Show()
@ -46,6 +40,10 @@ func Start() {
pomodoro := &shared.ServerMessage
keyboard.Listen(func(key keys.Key) (stop bool, err error) {
select {
case <-websocket.Done:
return true, nil
default:
switch key.String() {
case "space":
if !pomodoro.Ongoing {
@ -69,12 +67,12 @@ func Start() {
}
return false, nil
case "q":
interrupt <- os.Interrupt
return true, nil
}
}
return false, nil
})
websocket.WaitForDisconnect(conn, interrupt)
websocket.Disconnect(conn)
}

View file

@ -3,7 +3,6 @@ package websocket
import (
"github.com/charmbracelet/log"
"github.com/gorilla/websocket"
"os"
"time"
)
@ -18,13 +17,12 @@ func Connect(url string) *websocket.Conn {
return conn
}
func WaitForDisconnect(conn *websocket.Conn, interrupt chan os.Signal) {
for {
func Disconnect(conn *websocket.Conn) {
select {
case <-Done:
// session closed by remote
return
case <-interrupt:
default:
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
@ -34,5 +32,4 @@ func WaitForDisconnect(conn *websocket.Conn, interrupt chan os.Signal) {
}
return
}
}
}