ChronoTomato/internal/websocket/connect.go

38 lines
838 B
Go
Raw Normal View History

2024-10-22 11:13:41 +00:00
package websocket
import (
"time"
"github.com/gorilla/websocket"
ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
2024-10-22 11:13:41 +00:00
)
// New websocket client
type Client ChronoTomato.GoTomatoClient
2024-10-30 10:03:18 +00:00
// Connects to websocket
func Connect(url string) Client {
2024-10-22 11:13:41 +00:00
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
return Client{Conn: conn, Server: url, LastErr: err}
}
2024-10-30 10:03:18 +00:00
// Disconnects from websocket
func (c Client) Disconnect() {
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
if c.Connected() {
c.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
2024-10-22 11:13:41 +00:00
select {
case <-Done:
case <-time.After(time.Second):
2024-10-22 11:13:41 +00:00
}
}
return
2024-10-22 11:13:41 +00:00
}
func (c Client) Connected() bool {
return c.Conn != nil
}