How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Echo · Go

Fix WebSocketError: websocket: close 1006 (abnormal closure): unexpected EOF in Echo

This error occurs when a WebSocket connection closes unexpectedly without a proper close handshake, typically because the client disconnected, a proxy timed out, or the server did not handle read errors gracefully. Fix it by implementing proper close handling, setting read deadlines with pong handlers, and distinguishing normal disconnects from real errors.

Reading the Stack Trace

2024/03/15 17:00:30 echo: GET /ws -> main.handleWS | 101 | 45002.104ms | 127.0.0.1 goroutine 34 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.handleWS({0x1029e4f80, 0x14000226000}) /app/handlers/ws.go:25 +0x2d8 github.com/gorilla/websocket.(*Conn).ReadMessage(0x14000196040) /go/pkg/mod/github.com/gorilla/websocket@v1.5.1/conn.go:492 +0x48 github.com/gorilla/websocket.(*Conn).NextReader(0x14000196040) /go/pkg/mod/github.com/gorilla/websocket@v1.5.1/conn.go:460 +0x194

Here's what each line means:

Common Causes

1. No read deadline or ping/pong handling

Without ping/pong keepalive, the server cannot detect dead connections until a read fails.

func handleWS(c echo.Context) error {
	conn, _ := upgrader.Upgrade(c.Response(), c.Request(), nil)
	defer conn.Close()
	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			log.Println("error:", err) // logs every normal disconnect as error
			break
		}
		conn.WriteMessage(websocket.TextMessage, msg)
	}
	return nil
}

2. All close errors treated as failures

The handler logs normal browser tab closes as errors, making monitoring noisy.

_, msg, err := conn.ReadMessage()
if err != nil {
	log.Printf("WEBSOCKET ERROR: %v", err) // includes normal closes
	break
}

3. Write to closed connection

The server tries to write a message after the client has disconnected, causing a write error.

func broadcast(clients map[*websocket.Conn]bool, msg []byte) {
	for conn := range clients {
		conn.WriteMessage(websocket.TextMessage, msg) // may be closed
	}
}

The Fix

Implement ping/pong keepalive to detect dead connections proactively. Set read deadlines that reset on pong receipt. Use IsUnexpectedCloseError to filter normal disconnects from actual errors, reducing log noise.

Before (broken)
func handleWS(c echo.Context) error {
	conn, _ := upgrader.Upgrade(c.Response(), c.Request(), nil)
	defer conn.Close()
	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			log.Println("error:", err)
			break
		}
		conn.WriteMessage(websocket.TextMessage, msg)
	}
	return nil
}
After (fixed)
const (
	pongWait   = 60 * time.Second
	pingPeriod = (pongWait * 9) / 10
)

func handleWS(c echo.Context) error {
	conn, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "websocket upgrade failed")
	}
	defer conn.Close()

	conn.SetReadDeadline(time.Now().Add(pongWait))
	conn.SetPongHandler(func(string) error {
		conn.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})

	// Ping ticker
	ticker := time.NewTicker(pingPeriod)
	defer ticker.Stop()

	go func() {
		for range ticker.C {
			if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(10*time.Second)); err != nil {
				return
			}
		}
	}()

	for {
		msgType, msg, err := conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
				log.Printf("unexpected ws close: %v", err)
			}
			break
		}
		if err := conn.WriteMessage(msgType, msg); err != nil {
			break
		}
	}
	return nil
}

Testing the Fix

package handlers_test

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/gorilla/websocket"
	"github.com/labstack/echo/v4"
	"github.com/stretchr/testify/assert"
)

func TestWebSocket_EchoMessage(t *testing.T) {
	e := echo.New()
	e.GET("/ws", handleWS)
	s := httptest.NewServer(e)
	defer s.Close()

	url := "ws" + strings.TrimPrefix(s.URL, "http") + "/ws"
	conn, _, err := websocket.DefaultDialer.Dial(url, nil)
	assert.NoError(t, err)
	defer conn.Close()

	conn.WriteMessage(websocket.TextMessage, []byte("hello"))
	_, msg, err := conn.ReadMessage()
	assert.NoError(t, err)
	assert.Equal(t, "hello", string(msg))
}

func TestWebSocket_CleanClose(t *testing.T) {
	e := echo.New()
	e.GET("/ws", handleWS)
	s := httptest.NewServer(e)
	defer s.Close()

	url := "ws" + strings.TrimPrefix(s.URL, "http") + "/ws"
	conn, _, err := websocket.DefaultDialer.Dial(url, nil)
	assert.NoError(t, err)

	err = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
	assert.NoError(t, err)
}

Run your tests:

go test ./handlers/... -v

Pushing Through CI/CD

git checkout -b fix/echo-websocket-error,git add handlers/ws.go handlers/ws_test.go,git commit -m "fix: add ping/pong keepalive and graceful close handling for WebSocket",git push origin fix/echo-websocket-error

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.22'
      - run: go mod download
      - run: go vet ./...
      - run: go test ./... -race -coverprofile=coverage.out
      - run: go build ./...

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

go get github.com/bugstack/sdk

Step 2: Initialize

import "github.com/bugstack/sdk"

func init() {
  bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run go test ./... locally to confirm WebSocket lifecycle works.
  2. Open a pull request with the keepalive changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify WebSocket stability in staging.

Frequently Asked Questions

BugStack tests WebSocket connection lifecycle including clean close, abnormal close, and ping/pong keepalive scenarios before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

1006 means the connection was closed abnormally without a close frame. This typically happens when the client browser tab is closed or a network interruption occurs.

Configure your proxy (Nginx/ALB) to upgrade WebSocket connections and set appropriate timeouts. Nginx needs proxy_set_header Upgrade and proxy_set_header Connection directives.