在websocket握手中设置Cookie

时间:2016-05-07 00:00:22

标签: go

在websocket握手期间,如何在Set-Cookie响应中添加Upgrade

我尝试了以下代码

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)
}

握手已成功完成,但响应中没有Set-Cookie HTTP标头。

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

根据RFC6455,这应该有效

  

也可能存在其他标题字段,例如Cookie

我在NodeJS中没有遇到这个问题。

1 个答案:

答案 0 :(得分:0)

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)