猿问

在 websocket 握手中设置 Cookie

在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 中没有这个问题。


小怪兽爱吃肉
浏览 675回答 1
1回答

当年话下

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)
随时随地看视频慕课网APP

相关分类

Go
我要回答