ds753947 2016-05-07 00:00
浏览 791
已采纳

Websocket握手中的Set-Cookie

During websocket handshake, how can I add Set-Cookie in the Upgrade response?

I tried the following code

import (
    //"encoding/json"
    "golang.org/x/net/websocket"
    //"io"
    "log"
    "net/http"
)

func main() {

    http.HandleFunc("/v2", onV2Handshake)

    //  Ports below 1024 can be opened only by root.
    err := http.ListenAndServe(":8080", nil)
    // err := http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
    if err != nil {
        log.Panicln(err)
    }
}

func EchoServer(ws *websocket.Conn) {
    //io.Copy(ws, ws)
}

func onV2Handshake(writer http.ResponseWriter, req *http.Request) {
    cookie := http.Cookie{Name: "_c_id_", Value: "abcd", Path: "/", HttpOnly: true, Secure: false}
    http.SetCookie(writer, &cookie)

    server := websocket.Server{Handler: websocket.Handler(EchoServer)}
    server.ServeHTTP(writer, req)
}

The handshake is done successfully but there is no Set-Cookie HTTP header in response.

Connection:Upgrade
Sec-WebSocket-Accept:wWtU5pygFsiY0aTzMRzJEQcgnZc=
Sec-WebSocket-Protocol:wamp.2.json
Upgrade:websocket

According to RFC6455, this should work

Additional header fields may also be present, such as cookies

I don't have this problem in NodeJS.

  • 写回答

1条回答 默认 最新

  • douke9545 2016-05-07 00:48
    关注
    cookie := http.Cookie{Name: "_c_id_", Value: "abcd", Path: "/", HttpOnly: true, Secure: false}
    
    server := websocket.Server{Handler: websocket.Handler(EchoServer)}
    server.Config.Header = make(map[string][]string)
    server.Config.Header.Set("Set-Cookie", cookie.String())
    server.ServeHTTP(writer, req)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog