olahol/melody

Proper way

hugows opened this issue · 2 comments

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.

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

Thank you for answering this question @siteshen.