reid 2 роки тому
батько
коміт
7b7cb69ea6
3 змінених файлів з 26 додано та 7 видалено
  1. 23 7
      broadcast/broadcast.go
  2. 1 0
      config/config.go
  3. 2 0
      ws/ws.go

+ 23 - 7
broadcast/broadcast.go

@@ -5,6 +5,7 @@ import (
 	"goseg/structs"
 	"log/slog"
 	"os"
+	"reflect"
 	"sync"
 
 	"github.com/gorilla/websocket"
@@ -17,6 +18,11 @@ var (
 	mu             sync.RWMutex // synchronize access to broadcastState
 )
 
+func init(){
+	// initialize broadcastState global var
+	return
+}
+
 // adds ws client
 func RegisterClient(conn *websocket.Conn) {
 	clients[conn] = true
@@ -27,18 +33,28 @@ func UnregisterClient(conn *websocket.Conn) {
 	delete(clients, conn)
 }
 
-// update the state and broadcast it to all clients
-// ex:
-// newState := structs.AuthBroadcast{ /* ... */ }
-// broadcast.UpdateState(newState)
-func UpdateState(newState structs.AuthBroadcast) {
+// update broadcastState with a map of items
+func UpdateStateWithMap(values map[string]interface{}) error {
 	mu.Lock()
 	defer mu.Unlock()
-	broadcastState = newState
+	v := reflect.ValueOf(&broadcastState).Elem()
+	for key, value := range values {
+		// we are matching the map key with the broadcastState item
+		field := v.FieldByName(key)
+		if !field.IsValid() || !field.CanSet() {
+			return fmt.Errorf("field %s does not exist or is not settable", key)
+		}
+		val := reflect.ValueOf(value)
+		if field.Type() != val.Type() {
+			return fmt.Errorf("type mismatch for field %s: expected %s, got %s", key, field.Type(), val.Type())
+		}
+		field.Set(val)
+	}
 	broadcastToClients()
+	return nil
 }
 
-// mutex return broadcast state
+// return broadcast state
 func GetState() structs.AuthBroadcast {
 	mu.Lock()
 	defer mu.Unlock()

+ 1 - 0
config/config.go

@@ -94,6 +94,7 @@ func UpdateConf(values map[string]interface{}) error {
 		logger.Error(errmsg)
 		return err
 	}
+	// update the globalConfig var
 	if err := json.Unmarshal(updatedJSON, &globalConfig); err != nil {
 		errmsg := fmt.Sprintf("Error updating global config: %v", err)
 		logger.Error(errmsg)

+ 2 - 0
ws/ws.go

@@ -76,6 +76,8 @@ func WsHandler(w http.ResponseWriter, r *http.Request) {
 			logger.Info("Urbit")
 		case "support":
 			logger.Info("Support")
+		case "broadcast":
+			broadcast.broadcastToClients()
 		default:
 			errmsg := fmt.Sprintf("Unknown request type:", payload.Type)
 			logger.Warn(errmsg)