GoTomato/cmd/server/main.go
Sebastian Mark ab2e8c161d feat: implement stale client removal after timeout
- add goroutine to remove stale clients from the connection pool
- update client struct to track `LastPong` time
- set write deadline for websocket connections
- move package variables and const to `vars.go`
- log additional information when broadcasting errors

🤖
2024-11-21 21:48:57 +01:00

67 lines
2 KiB
Go

package server
import (
"flag"
"fmt"
"github.com/gorilla/handlers"
"net/http"
"os"
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/internal/metadata"
"git.smsvc.net/pomodoro/GoTomato/internal/shared"
"git.smsvc.net/pomodoro/GoTomato/internal/websocket"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
var (
// define CLI flags
listenAddress = flag.String("listenAddress", shared.DefaultServerConfig.ListenAddress, "IP address to listen on")
listenPort = flag.Int("listenPort", shared.DefaultServerConfig.ListenPort, "Port to listen on")
password = flag.String("password", "", "Control password for pomodoro session (optional)")
showVersion = flag.Bool("version", false, "Output version")
)
// Start the pomodoro server
func Start() {
// Update usage output
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", "GoTomato")
flag.PrintDefaults()
fmt.Println("\nPoint your client to 'ws://<listenAddress>:<listenPort>'")
}
flag.Parse()
// show server and protocl version and exit
if *showVersion {
fmt.Printf("GoTomato v%s\n", metadata.GoTomatoVersion)
fmt.Printf("Protocol-Version: %s\n", metadata.ProtocolVersion)
os.Exit(0)
}
// set server config
serverConfig := models.ServerConfig{
ListenAddress: *listenAddress,
ListenPort: *listenPort,
}
shared.PomodoroPassword = *password
// define listen address for websocket
listen := fmt.Sprintf("%s:%d", serverConfig.ListenAddress, serverConfig.ListenPort)
// start connection handler and broadcast
r := http.NewServeMux()
r.HandleFunc("/", websocket.HandleConnection)
go websocket.SendPermanentBroadCastMessage()
go websocket.RemoveStaleClients()
helper.Logger.Info("GoTomato started", "version", metadata.GoTomatoVersion)
helper.Logger.Info("Websocket listening", "address", listen)
// start the listener
err := http.ListenAndServe(listen, handlers.ProxyHeaders(r))
if err != nil {
helper.Logger.Fatal("Error starting server:", "msg", err)
}
}