gpt4 book ai didi

go - 在 websocket 握手中设置 Cookie

转载 作者:IT王子 更新时间:2023-10-29 02:23:14 29 4
gpt4 key购买 nike

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

我试过下面的代码

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 header 。

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

根据 RFC6455 , 这应该有效

Additional header fields may also be present, such as cookies

我在 NodeJS 中没有这个问题。

最佳答案

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)

关于go - 在 websocket 握手中设置 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083025/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com