'How to properly refuse websocket upgrade request?

Sometimes I want to refuse a http client's request to upgrade connection to websocket.


Code

(using go's Gin and gorilla/websocket framework:)

To allow upgrade:

c, err := ctl.upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
err = c.WriteJSON(resp)

To refuse upgrade (due to invalid request params):

if contentId == "" || !exists {
    // FIXME: provide response in a way that ws client can recognize & show tip?
    ctx.String(http.StatusBadRequest, "invalid or non-existing contentId")
    return
}

Explaination: Here to refuse the upgrade I just return a http 400 code, then terminate the connection, and didn't do the upgrade at all.


The issue

The problem to refuse websocket upgrade request with about code is that, the websocket client (e.g js), can't read data (text or json) in my response.

Code - client-side (js):

ws.onerror = function (evt) {
    // TOOD: handle error, (e.g print error msg?),
    print("ERROR");
}

It does print the "ERROR" on refuse, but after checking chrome developer tool about the evt object, can't find a way to get server response data, so I can't show tip to frontend UI with reason of refuse.


Questions

  • How to refuse websocket upgrade request properly, and let client be able to receive the returned reason/data ? (e.g client is js, server is go / gin / gorilla/websocket).
  • Is there a better way to refuse websocket upgrade request, other than return http code like 400?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source