Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go- infinite for loop in a handler

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    }
}

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading