Skip to content

WebSockets ​

Use a WebSocket when a client needs a connection that can carry messages in both directions. Register it with web.NewWebSocketRoute in the same controller route list as your HTTP endpoints.

This example extends Your First Route with a connection that echoes one JSON message, then closes.

Add the Handler ​

Create internal/users/websocket.go.

go
// Package users keeps user endpoints together.
package users

import "github.com/goforj/web"

// EchoMessage defines the JSON exchange for the echo endpoint.
type EchoMessage struct {
	Text string `json:"text"`
}

// Echo closes the connection after one request and response.
func (c *Controller) Echo(_ web.Context, conn web.WebSocketConn) error {
	defer conn.Close()

	var message EchoMessage
	if err := conn.ReadJSON(&message); err != nil {
		return err
	}
	return conn.WriteJSON(message)
}

In internal/users/controller.go, add the WebSocket route to Controller.Routes. Keep the other routes that already belong to the controller.

go
// Routes exposes the user lookup and the WebSocket echo endpoint.
func (c *Controller) Routes() []web.Route {
	return []web.Route{
		web.NewRoute(http.MethodGet, "/users/:id", c.Show),
		web.NewWebSocketRoute("/users/echo", c.Echo),
	}
}

The existing App route group adds /api/v1, so the connection URL is ws://localhost:3000/api/v1/users/echo. The handler runs after the upgrade. Return errors from message operations and close the connection when the handler finishes.

Test the Registered Route ​

Create internal/users/websocket_test.go. This test registers the controller routes with the default Echo adapter and connects over a local HTTP server. It verifies the upgrade and JSON exchange together.

go
// Package users keeps user endpoints together.
package users

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

	"github.com/goforj/web"
	"github.com/goforj/web/adapter/echoweb"
	"github.com/gorilla/websocket"
)

// TestWebSocketEcho verifies the registered route through a real connection.
func TestWebSocketEcho(t *testing.T) {
	adapter := echoweb.New()
	controller := NewController(NewService())
	groups := []web.RouteGroup{
		web.NewRouteGroup("/api/v1", controller.Routes()),
	}
	if err := web.RegisterRoutes(adapter.Router(), groups); err != nil {
		t.Fatal(err)
	}
	server := httptest.NewServer(adapter)
	defer server.Close()

	dialer := websocket.Dialer{HandshakeTimeout: 5 * time.Second}
	url := "ws" + strings.TrimPrefix(server.URL, "http") + "/api/v1/users/echo"
	headers := http.Header{"Origin": []string{server.URL}}
	conn, _, err := dialer.Dial(url, headers)
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
		t.Fatal(err)
	}

	want := EchoMessage{Text: "hello"}
	if err := conn.WriteJSON(want); err != nil {
		t.Fatal(err)
	}
	var got EchoMessage
	if err := conn.ReadJSON(&got); err != nil {
		t.Fatal(err)
	}
	if got != want {
		t.Fatalf("message = %+v, want %+v", got, want)
	}
}

List the registered routes from the Project root.

bash
forj route:list

Look for /api/v1/users/echo. To run the echo test itself, use go test ./internal/users -run TestWebSocketEcho.

Connect from the Browser ​

With forj dev running, open the browser console on http://localhost:3000/api/v1/users/42. Connect to the echo route and send a message.

js
const socket = new WebSocket('ws://localhost:3000/api/v1/users/echo')
socket.onopen = () => socket.send(JSON.stringify({ text: 'hello' }))
socket.onmessage = (event) => console.log(event.data)
// {"text":"hello"}

Use your configured port in both URLs. The default adapter accepts an absent Origin header or an origin whose host matches the request host. A page on another port has a different origin and is rejected. CORS middleware does not override the WebSocket origin check.

For a public endpoint, authenticate and authorize the upgrade with route middleware. Use wss:// behind HTTPS, configure the proxy to forward WebSocket upgrades, and set explicit read limits and deadlines for long-lived connections. The connection's Native() method exposes the adapter connection when you need those controls. This one-message example closes each connection after its reply.

See WebSocket route APIs for the connection contract and Middleware for route policies.