为了账号安全,请及时绑定邮箱和手机立即绑定

在 websocket 握手中设置 Cookie

在 websocket 握手中设置 Cookie

Go
小怪兽爱吃肉 2022-01-10 14:22:59
在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:UpgradeSec-WebSocket-Accept:wWtU5pygFsiY0aTzMRzJEQcgnZc=Sec-WebSocket-Protocol:wamp.2.jsonUpgrade:websocket根据RFC6455,这应该有效还可能存在其他标头字段,例如 cookie我在 NodeJS 中没有这个问题。
查看完整描述

1 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

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)


查看完整回答
反对 回复 2022-01-10
  • 1 回答
  • 0 关注
  • 674 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信