Home > Software design >  Go- infinite for loop in a handler
Go- infinite for loop in a handler

Time:04-13

I am having difficulty understanding the implementation of something that I did using a blog

I am creating a new websocket connection, in which, I am running an infinite loop

As per my understanding

  • The infinite loop should run indefinitely regardless the message received by the websocket

But it doesn't, the logic inside it is only triggered when a "new payload/message" is sent from the frontend ws connection:

func (s *SocketHandlers) NewConnectionHandler(w http.ResponseWriter, r *http.Request) {
    // upgrade the http request to a ws request
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer ws.Close()
    for { // infinite loop
        log.Println("Checking to see if this repeats") // <=== PRINTS ONLY ONCE!
        var payload core.NewSessionPayload
        if err := ws.ReadJSON(&payload); err != nil {
            log.Println("Cannot read socket conection payload")
            log.Fatal(err)
        }
        s.clientsMap[ws] = core.ClientNode{
            Active:   true,
            Username: payload.Username,
        }
        // broadcast the latest users list to all the users
        s.broadcaster <- payload.Username
    }
}

CodePudding user response:

the point is here s.broadcaster <- payload.Username it's trying to get a value from a channel.

you can read more about channels here https://gobyexample.com/channels.

Channel operations (i.e. write or read) are blocking in nature.

This means:

  • When we send data into the channel using a GoRoutine, it will be blocked until the data is consumed by another GoRoutine.
  • When we receive data from a channel using a GoRoutine, it will be blocked until the data is available in the channel.
  • Related