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

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 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用