mlblive/cmd/internal/statsapi/websocket.go

75 lines
1.7 KiB
Go

/*
Copyright © 2024 filifa
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package statsapi
import (
"net/url"
"time"
"github.com/gorilla/websocket"
)
type Push struct {
UpdateId string
}
type GamedayWebsocket struct {
baseURL url.URL
*websocket.Conn
}
func NewGamedayWebsocket(gamePk string) (GamedayWebsocket, error) {
ws := GamedayWebsocket{
baseURL: url.URL{
Scheme: "wss",
Host: "ws.statsapi.mlb.com",
},
}
err := ws.init(gamePk)
return ws, err
}
func (g *GamedayWebsocket) init(gamePk string) error {
endpoint := url.URL{
Path: "api/v1/game/push/subscribe/gameday/" + gamePk,
}
url := g.baseURL.ResolveReference(&endpoint)
conn, _, err := websocket.DefaultDialer.Dial(url.String(), nil)
g.Conn = conn
return err
}
func (g *GamedayWebsocket) SendKeepAlive() error {
msg := []byte("Gameday5")
err := g.Conn.WriteMessage(websocket.TextMessage, msg)
return err
}
func (g *GamedayWebsocket) KeepAlive(interval time.Duration, ch chan<- error) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
err := g.SendKeepAlive()
if err != nil {
ch <- err
}
}
}