olahol / melody

:notes: Minimalist websocket framework for Go
BSD 2-Clause "Simplified" License
3.75k stars 366 forks source link

Gophers example writing X and Y values #95

Closed Unwarped closed 4 months ago

Unwarped commented 4 months ago

I was studying the examples and looking at the Gophers demo I see that it retrieves the player pointer from session storage, and then writes the X and Y values. Is this thread safe, or would it be best to have some kind of lock? ( Potential race condition ) I know it's just an example, but I'm new to Go and trying to learn best practices.

m.HandleMessage(func(s *melody.Session, msg []byte) {
        p := strings.Split(string(msg), " ")
        value, exists := s.Get("info")

        if len(p) != 2 || !exists {
            return
        }

        info := value.(*GopherInfo)
        info.X = p[0] ⚫
        info.Y = p[1] ⚫

        m.BroadcastOthers([]byte("set "+info.ID+" "+info.X+" "+info.Y), s)
    })
olahol commented 4 months ago

You are right. I've updated the Gophers demo to be more straight forward. Thank you.