ChronoTomato/internal/websocket/connect.go
Sebastian Mark 6187122b81 feat: refactor client methods
- change `ProcessServerMessages` to use receiver instead of parameter
- update `Disconnect` method to use receiver for better encapsulation
- move `Client` definition to `connect.go`

🤖
2024-10-30 09:51:59 +01:00

39 lines
888 B
Go

package websocket
import (
"github.com/charmbracelet/log"
"github.com/gorilla/websocket"
"time"
ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
)
type Client ChronoTomato.GoTomatoClient // New websocket client
func Connect(url string) Client {
log.Info("Connected ó°–Ÿ ", "host", url)
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
log.Fatal("Dial error!", "reason", err)
}
return Client{Conn: conn}
}
func (c Client) Disconnect() {
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.
c.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
select {
case <-Done:
case <-time.After(time.Second):
}
return
}
}