olahol / melody

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

Proper way #33

Closed hugows closed 7 years ago

hugows commented 7 years ago

Hi guys,

love your API compared with gorilla/websockets. Also loved that you guys built on top of that solid base instead of doing everything from scratch.

Let me ask: is there a proper way to "deny" the upgrade? I will only allow authenticated users to open a websocket connection:

    r.Get("/ws", func(w http.ResponseWriter, r *http.Request) {
        var input struct {
            Token string `json:"token"`
        }

        if err := render.Bind(r, &input); err != nil {
            http.Error(w, http.StatusText(401), 401)
            return
        }
               ...

Again, thanks for the sweet project.

siteshen commented 7 years ago

Upgrade is triggered by m.HandleRequest() or m.HandleRequestWithKeys(), so the following code should work:

func validToken(string) bool { return true }

func ServeWs(w http.ResponseWriter, r *http.Request) {
    token := "token from client"
    if !validToken(token) {
        w.WriteHeader(401)
        return
    }

    m := melody.New()
    m.HandleRequestWithKeys(w, r, map[string]interface{}{"token": token})
}
olahol commented 7 years ago

Thank you for answering this question @siteshen.