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

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
    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)
    
    点赞 评论

相关推荐