Handling the upgrade of a request client-side

34 Views Asked by At

I'm probably being stupid here, but I am upgrading a HTML Request to a WS, with Gorilla Mux, and can't seem to figure out how to access the WebSocket on the Webpage after upgrade,

func loadSecureThing(w http.ResponseWriter, r *http.Request) {
    if helpers.IsLocalRequest(r) {
        http.ServeFile(w, r, "secure-login-thing.html")
        c, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            fmt.Println("Upgrade error: Please contact server admin.")
            return
        }
         //Authentication stuff
        defer c.Close()

I've looked up how to handle upgrade but I see them opening a new WS connection with

const wss = new WebSocket('wss://route');

socket.onopen = function (event) {
    document.getElementById("submit-btn").addEventListener("click", function () {
        //send auth stuff with JWT
    })
}

This creates a new WSS, when we already have one that's been upgraded, so im confused how I would access this upgraded request on the client side.

I expected to be able to send messages through this WSS connection from the server, after the initial request has been upgraded on the client side,

Thank you friends :)

1

There are 1 best solutions below

0
Steffen Ullrich On

The creation of a Websocket is initiated by the client by a special upgrade request. A server cannot simply upgrade an arbitrary request to Websocket and then return this back to the client, instead only explicit requests for a Websocket can be upgraded. It is also not possible to serve a normal HTTP response before upgrading, instead the only possible response is either a successful upgrade or a failure.