duanrui3480 2019-08-26 12:34
浏览 748

我如何通过websocket js发送标头,而无需响应

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

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误