broadcast.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package broadcast
  2. import (
  3. "encoding/json"
  4. "goseg/config"
  5. "goseg/structs"
  6. "log/slog"
  7. "os"
  8. "reflect"
  9. "sync"
  10. "fmt"
  11. "github.com/gorilla/websocket"
  12. )
  13. var (
  14. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  15. clients = make(map[*websocket.Conn]bool)
  16. broadcastState structs.AuthBroadcast
  17. mu sync.RWMutex // synchronize access to broadcastState
  18. )
  19. func init(){
  20. // initialize broadcastState global var
  21. config := config.Conf()
  22. broadcast, err := bootstrapBroadcastState(config)
  23. if err != nil {
  24. errmsg := fmt.Sprintf("Unable to initialize broadcast: %v",err)
  25. panic(errmsg)
  26. }
  27. broadcastState = broadcast
  28. }
  29. // adds ws client
  30. func RegisterClient(conn *websocket.Conn) {
  31. clients[conn] = true
  32. }
  33. // remove ws client
  34. func UnregisterClient(conn *websocket.Conn) {
  35. delete(clients, conn)
  36. }
  37. // take in config file and addt'l info to initialize broadcast
  38. func bootstrapBroadcastState(config structs.SysConfig) (structs.AuthBroadcast, error) {
  39. var res structs.AuthBroadcast
  40. return res, nil
  41. }
  42. // update broadcastState with a map of items
  43. func UpdateBroadcastState(values map[string]interface{}) error {
  44. mu.Lock()
  45. defer mu.Unlock()
  46. v := reflect.ValueOf(&broadcastState).Elem()
  47. for key, value := range values {
  48. // we are matching the map key with the broadcastState item
  49. field := v.FieldByName(key)
  50. if !field.IsValid() || !field.CanSet() {
  51. return fmt.Errorf("field %s does not exist or is not settable", key)
  52. }
  53. val := reflect.ValueOf(value)
  54. if field.Type() != val.Type() {
  55. return fmt.Errorf("type mismatch for field %s: expected %s, got %s", key, field.Type(), val.Type())
  56. }
  57. field.Set(val)
  58. }
  59. BroadcastToClients()
  60. return nil
  61. }
  62. // return broadcast state
  63. func GetState() structs.AuthBroadcast {
  64. mu.Lock()
  65. defer mu.Unlock()
  66. return broadcastState
  67. }
  68. // broadcast the global state to all clients
  69. func BroadcastToClients() error {
  70. broadcastJson, err := json.Marshal(broadcastState)
  71. if err != nil {
  72. logger.Error("Error marshalling response:", err)
  73. return err
  74. }
  75. for client := range clients {
  76. if err := client.WriteMessage(websocket.TextMessage, broadcastJson); err != nil {
  77. logger.Error("Error writing response:", err)
  78. return err
  79. }
  80. }
  81. return nil
  82. }