Fix WebSocketUpgradeError: websocket: request origin not allowed by Upgrader.CheckOrigin in Gin
This error occurs when the gorilla/websocket Upgrader rejects the WebSocket handshake because the request origin does not match the server's host. Fix it by configuring a CheckOrigin function on the Upgrader that validates allowed origins, and handle the upgrade error to return a proper HTTP response instead of silently failing.
Reading the Stack Trace
Here's what each line means:
- github.com/gorilla/websocket.(*Upgrader).Upgrade(0x14000118300, {0x1029e4f80, 0x140001c40e0}, 0x140002b4000, {0x0, 0x0}): The WebSocket Upgrader at server.go:155 rejects the upgrade because CheckOrigin returned false for the request's Origin header.
- main.handleWebSocket(0x14000226000) /app/handlers/ws.go:18 +0x1c4: The WebSocket handler at line 18 calls Upgrade which fails, but the error is not being handled.
- github.com/gin-gonic/gin.(*Context).Next(0x14000226000): Gin passes control to the WebSocket handler in the middleware chain.
Common Causes
1. Default CheckOrigin rejects cross-origin requests
The default Upgrader.CheckOrigin requires the Origin header to match the Host header, rejecting cross-origin WebSocket connections.
var upgrader = websocket.Upgrader{} // default CheckOrigin rejects cross-origin
func handleWebSocket(c *gin.Context) {
conn, _ := upgrader.Upgrade(c.Writer, c.Request, nil)
defer conn.Close()
for {
_, msg, _ := conn.ReadMessage()
conn.WriteMessage(websocket.TextMessage, msg)
}
}
2. Error from Upgrade not handled
The error from upgrader.Upgrade is ignored, causing the handler to proceed with a nil connection and panic.
conn, _ := upgrader.Upgrade(c.Writer, c.Request, nil) // ignoring error
conn.WriteMessage(websocket.TextMessage, []byte("hello")) // nil pointer panic
3. Connection not properly closed on error
The WebSocket connection is never closed on read/write errors, leaking goroutines and file descriptors.
func handleWebSocket(c *gin.Context) {
conn, _ := upgrader.Upgrade(c.Writer, c.Request, nil)
for {
_, msg, err := conn.ReadMessage()
if err != nil {
break // conn never closed
}
conn.WriteMessage(websocket.TextMessage, msg)
}
}
The Fix
Configure CheckOrigin to validate allowed origins explicitly. Handle the Upgrade error to avoid nil pointer panics. Check read/write errors in the message loop and use IsUnexpectedCloseError to distinguish normal disconnects from actual errors.
var upgrader = websocket.Upgrader{}
func handleWebSocket(c *gin.Context) {
conn, _ := upgrader.Upgrade(c.Writer, c.Request, nil)
defer conn.Close()
for {
_, msg, _ := conn.ReadMessage()
conn.WriteMessage(websocket.TextMessage, msg)
}
}
var allowedOrigins = map[string]bool{
"http://localhost:3000": true,
"https://yourdomain.com": true,
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return allowedOrigins[r.Header.Get("Origin")]
},
}
func handleWebSocket(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("websocket upgrade failed: %v", err)
return
}
defer conn.Close()
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
log.Printf("websocket error: %v", err)
}
break
}
if err := conn.WriteMessage(msgType, msg); err != nil {
log.Printf("websocket write error: %v", err)
break
}
}
}
Testing the Fix
package handlers_test
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestWebSocket_ValidOrigin(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/ws", handleWebSocket)
s := httptest.NewServer(r)
defer s.Close()
url := "ws" + strings.TrimPrefix(s.URL, "http") + "/ws"
header := http.Header{"Origin": []string{"http://localhost:3000"}}
conn, resp, err := websocket.DefaultDialer.Dial(url, header)
assert.NoError(t, err)
assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)
conn.Close()
}
func TestWebSocket_BlockedOrigin(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/ws", handleWebSocket)
s := httptest.NewServer(r)
defer s.Close()
url := "ws" + strings.TrimPrefix(s.URL, "http") + "/ws"
header := http.Header{"Origin": []string{"http://evil.com"}}
_, resp, err := websocket.DefaultDialer.Dial(url, header)
assert.Error(t, err)
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}
Run your tests:
go test ./handlers/... -v
Pushing Through CI/CD
git checkout -b fix/gin-websocket-error,git add handlers/ws.go handlers/ws_test.go,git commit -m "fix: configure CheckOrigin and handle WebSocket upgrade errors",git push origin fix/gin-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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Run go test ./... locally to confirm WebSocket connections work.
- Open a pull request with the WebSocket handler changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify WebSocket connections work in staging.
Frequently Asked Questions
BugStack validates WebSocket upgrade behavior with multiple origin scenarios, tests connection lifecycle, and ensures no goroutine leaks 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.
No. Unlike REST APIs, WebSocket connections bypass CORS. A permissive CheckOrigin allows any site to connect to your WebSocket server on behalf of an authenticated user.
Use a pub/sub system like Redis to broadcast messages between server instances. Each server manages its own connections and relays messages through the shared broker.