我正在运行一个将网络钩子转发到网络平台的脚本。将 Webhook 发送到 WebSocket 的部件会检查非活动连接,并在转发 Webhook 时尝试删除它们,有时会失败并显示以下错误:
http: panic serving 10.244.38.169:40958: runtime error: slice bounds out of range
(IP/端口总是不同的,这只是一个示例。
相关代码:
// Map holding all Websocket clients and the endpoints they are subscribed to
var clients = make(map[string][]*websocket.Conn)
var upgrader = websocket.Upgrader{}
// function to execute when a new client connects to the websocket
func handleClient(w http.ResponseWriter, r *http.Request, endpoint string) {
conn, err := upgrader.Upgrade(w, r, nil)
// ...
// Add client to endpoint slice
clients[endpoint] = append(clients[endpoint], conn)
}
// function to send a webhook to a websocket endpoint
func handleHook(w http.ResponseWriter, r *http.Request, endpoint string) {
msg := Message{}
// ...
// Get all clients listening to the current endpoint
conns := clients[endpoint]
if conns != nil {
for i, conn := range conns {
if conn.WriteJSON(msg) != nil {
// Remove client and close connection if sending failed
conns = append(conns[:i], conns[i+1:]...) // this is the line that sometimes triggers the panic
conn.Close()
}
}
}
clients[endpoint] = conns
}
我不明白为什么迭代连接并附加它们有时会引发恐慌。
蓝山帝景
相关分类