chore: Improve WebSocket configuration and error handling

This commit is contained in:
skidoodle 2024-05-28 13:16:40 +02:00
parent d3d2cbd9d0
commit bec030816a

19
main.go
View file

@ -17,11 +17,18 @@ var (
clients = make(map[*websocket.Conn]bool) // Map to keep track of connected clients clients = make(map[*websocket.Conn]bool) // Map to keep track of connected clients
broadcast = make(chan *spotify.CurrentlyPlaying) // Channel for broadcasting currently playing track broadcast = make(chan *spotify.CurrentlyPlaying) // Channel for broadcasting currently playing track
upgrader = websocket.Upgrader{ upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true }, CheckOrigin: func(r *http.Request) bool { return true }, // Allow all origins
HandshakeTimeout: 10 * time.Second, // Timeout for WebSocket handshake
ReadBufferSize: 1024, // Buffer size for reading incoming messages
WriteBufferSize: 1024, // Buffer size for writing outgoing messages
Subprotocols: []string{"binary"}, // Supported subprotocols
Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) {
log.Printf("Error upgrading WebSocket connection: %v", reason)
},
} }
spotifyClient spotify.Client // Spotify API client spotifyClient spotify.Client // Spotify API client
tokenSource oauth2.TokenSource // OAuth2 token source tokenSource oauth2.TokenSource // OAuth2 token source
config *oauth2.Config // OAuth2 configuration config *oauth2.Config // OAuth2 configuration
) )
func main() { func main() {
@ -58,8 +65,8 @@ func main() {
// Log server start-up and initialize background tasks // Log server start-up and initialize background tasks
log.Println("Server started on :3000") log.Println("Server started on :3000")
go TrackFetcher() // Periodically fetch currently playing track from Spotify go TrackFetcher() // Periodically fetch currently playing track from Spotify
go MessageHandler() // Broadcast messages to connected clients go MessageHandler() // Broadcast messages to connected clients
// Start the HTTP server // Start the HTTP server
if err := http.ListenAndServe(":3000", nil); err != nil { if err := http.ListenAndServe(":3000", nil); err != nil {