2024-10-22 11:13:41 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/charmbracelet/log"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"time"
|
2024-10-30 07:28:22 +00:00
|
|
|
|
|
|
|
"git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
|
2024-10-22 11:13:41 +00:00
|
|
|
)
|
|
|
|
|
2024-10-30 07:28:22 +00:00
|
|
|
func Connect(url string) models.Client {
|
2024-10-22 11:13:41 +00:00
|
|
|
log.Info("Connected ó°–Ÿ ", "host", url)
|
|
|
|
|
|
|
|
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Dial error!", "reason", err)
|
|
|
|
}
|
|
|
|
|
2024-10-30 07:28:22 +00:00
|
|
|
return models.Client{Conn: conn}
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 07:28:22 +00:00
|
|
|
func Disconnect(client models.Client) {
|
2024-10-23 17:04:52 +00:00
|
|
|
select {
|
|
|
|
case <-Done:
|
|
|
|
// session closed by remote
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
// Cleanly close the connection by sending a close message and then
|
|
|
|
// waiting (with timeout) for the server to close the connection.
|
2024-10-30 07:28:22 +00:00
|
|
|
client.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
2024-10-22 11:13:41 +00:00
|
|
|
select {
|
|
|
|
case <-Done:
|
2024-10-23 17:04:52 +00:00
|
|
|
case <-time.After(time.Second):
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|
2024-10-23 17:04:52 +00:00
|
|
|
return
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|
|
|
|
}
|