I have js that is making a websocket connection to my go and i need to send a jwt so i have send it in the header but since my websocket is not making a respond chrome is not allowing me to make the request. So i need to either send a respond or set the header in a way that does not need one.
I have tried to wright on my http response in go but it did not work and i can not send it in URL because of security.
client:
if (window["WebSocket"]) {
conn = new WebSocket("ws://127.0.0.1:8080/trip/chat/ws?id={{ trip.id }}", "{{ jwt }}");
conn.protocol()
conn.onclose = function (evt) {
var item = document.createElement("div");
item.innerHTML = "<b>Connection closed.</b>";
appendLog(item);
};
conn.onmessage = function (evt) {
var messages = evt.data.split('
');
for (var i = 0; i < messages.length; i++) {
var item = document.createElement("div");
item.innerText = messages[i];
appendLog(item);
}
};
server:
func serveWs(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Yo"))
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
tknstr := r.Header.Get("Sec-WebSocket-Protocol")
claims := getTokenConntents(tknstr)
trip, ok := r.URL.Query()["id"]
if !ok {
log.Println("Url Param id is missing")
return
}
id, err := strconv.ParseInt(trip[0], 10, 64)
if err != nil {
log.Println(err)
return
}
log.Print("client made")
if _, ok := Hubs[trip[0]]; !ok {
hub := newHub()
go hub.run()
Hubs[trip[0]] = hub
}
if claims.Username != "" && claims.Trip == int(id) {
client := &Client{hub: Hubs[trip[0]], conn: conn, send: make(chan Message, 256), trip: int(id), claims: claims}
client.hub.register <- client
go client.serveLastMessages(int(id))
go client.writePump()
go client.readPump()
} else {
conn.Close()
}
}
and this is the error that my chrome sends: WebSocket connection to 'ws://127.0.0.1:8080/trip/chat/ws?id=7' failed: Error during WebSocket handshake: Unexpected response code: 200