Skip to content

BUG: plain HTTP request to a WebSocket route panics (unchecked type assertion + nil deref) #3862

Description

@junnhwan

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions