Simple Go WebSocket playground that serves a static test page and exposes a JSON-aware echo service for experimenting with WebSocket message handling patterns.
- Serves static assets from
web/and exposes/testand/wsendpoints. - Upgrades HTTP GET requests on
/wsto WebSocket connections using Gorilla WebSocket with strict origin checks forws://localhost:4000. - Echoes plain text messages with a running counter, supports
UPPER:andREVERSE:directives, and tracks message totals atomically. - Accepts JSON commands for basic math operations (
add,subtract,multiply,divide) and responds with structured JSON payloads. - Maintains healthy connections with ping/pong heartbeats, read deadlines, and graceful close handling.
- Go 1.25 or newer (
go env GOVERSIONshould report at least go1.25). - Make (optional) if you want the convenience targets in the provided
Makefile.
- Clone the repository and enter the project directory.
git clone https://github.com/alexdev404/ws-main.git cd ws-main - Download Go module dependencies.
go mod download
- Directly via Go:
go run ./cmd/web
- Or with the included Make target:
make run/web
The server listens on http://localhost:4000. Static files in web/ are served from the root; web/test.html is a ready-to-use client for trying the WebSocket API.
- Start the server.
- Open
http://localhost:4000/test.htmlin a browser. The page establishes a WebSocket connection tows://localhost:4000/ws. - Send messages using the input field:
- Plain text (
hello) echoes back as[Msg #N] hellowhereNis the global counter. - Prefix with
UPPER:to force uppercase (UPPER:hello→[Msg #N] HELLO). - Prefix with
REVERSE:to reverse the remaining text (REVERSE:abc→[Msg #N] cba). - Send JSON for math commands, e.g.
{"command":"add","a":3,"b":4}. The server responds with JSON:{"result":7,"command":"add"}. Division by zero and unknown commands return an error string.
- Plain text (
- Connections are limited to the allowed origin list; adjust
allowedOriginsininternal/ws/handler.goif you need to serve from a different host.
Execute the Go test suite:
go test ./...cmd/web/ # Entry point for the HTTP/WebSocket server
internal/ws/ # WebSocket handler, message processing helpers
web/ # Static assets including the WebSocket demo page
go.mod # Module definition and dependencies
Makefile # Convenience target for running the server
- Origin blocked: Ensure you access the app through
http://localhost:4000; otherwise update theallowedOriginsslice. - Port in use: Stop other services on port 4000 or change the port in
cmd/web/main.goand rebuild.