Bug description
A plain HTTP request to a route registered via app.WebSocket(...) reaches the WebSocket handler and can panic.
How it happens
App.WebSocket(route, handler) registers the route as a normal GET route:
Inside the generated handler:
connID := ctx.Request.Context().Value(websocket.WSConnectionKey).(string)
conn := a.httpServer.ws.GetWebsocketConnection(connID)
if conn.Conn == nil {
return nil, websocket.ErrorConnection
}
When a client sends a plain GET /ws (no Connection: Upgrade, no Upgrade: websocket headers), the WSHandlerUpgrade middleware does not add WSConnectionKey to the request context. The type assertion:
ctx.Request.Context().Value(websocket.WSConnectionKey).(string)
then panics with interface conversion: interface {} is nil, not string.
Even if that assertion were safe, GetWebsocketConnection("") returns nil, and the subsequent conn.Conn == nil would dereference nil.
Expected behavior
A non-WebSocket request to a WebSocket route should get a clean 4xx response (for example 400 Bad Request or websocket.ErrorConnection) instead of a panic.
Repro sketch
app := gofr.New()
app.WebSocket("/ws", func(ctx *gofr.Context) (any, error) {
return "ok", nil
})
// Plain GET without WebSocket upgrade headers.
// expected: clean error response
// actual: panic
Suggested fix direction
In App.WebSocket handler, use a safe type assertion and nil checks before dereferencing:
connID, ok := ctx.Request.Context().Value(websocket.WSConnectionKey).(string)
if !ok {
return nil, websocket.ErrorConnection
}
conn := a.httpServer.ws.GetWebsocketConnection(connID)
if conn == nil || conn.Conn == nil {
return nil, websocket.ErrorConnection
}
Notes
Bug description
A plain HTTP request to a route registered via
app.WebSocket(...)reaches the WebSocket handler and can panic.How it happens
App.WebSocket(route, handler)registers the route as a normal GET route:Inside the generated handler:
When a client sends a plain
GET /ws(noConnection: Upgrade, noUpgrade: websocketheaders), theWSHandlerUpgrademiddleware does not addWSConnectionKeyto the request context. The type assertion:then panics with
interface conversion: interface {} is nil, not string.Even if that assertion were safe,
GetWebsocketConnection("")returnsnil, and the subsequentconn.Conn == nilwould dereferencenil.Expected behavior
A non-WebSocket request to a WebSocket route should get a clean 4xx response (for example
400 Bad Requestorwebsocket.ErrorConnection) instead of a panic.Repro sketch
Suggested fix direction
In
App.WebSockethandler, use a safe type assertion and nil checks before dereferencing:Notes
WriteMessageToSocketnil panic, but this is a different code path (App.WebSocketroute handler).