-
Notifications
You must be signed in to change notification settings - Fork 0
Add websocket routing support #101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Suhaibinator
wants to merge
3
commits into
main
Choose a base branch
from
codex/add-support-for-websockets
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # WebSocket Support | ||
|
|
||
| SRouter can now register WebSocket endpoints alongside standard HTTP routes. WebSocket routes reuse the same middleware and authentication pipeline used by REST handlers, so cross-cutting behavior such as tracing, logging, rate limiting, and custom middleware still apply to the initial upgrade request. | ||
|
|
||
| ## Declaring a WebSocket route | ||
|
|
||
| Use `WebSocketRouteConfig` inside a `SubRouterConfig` just like any other `RouteDefinition`: | ||
|
|
||
| ```go | ||
| wsRoute := router.WebSocketRouteConfig{ | ||
| Path: "/echo", | ||
| Middlewares: []common.Middleware{loggingMiddleware}, | ||
| Handler: func(ctx context.Context, conn *websocket.Conn) { | ||
| for { | ||
| msgType, payload, err := conn.ReadMessage() | ||
| if err != nil { | ||
| return | ||
| } | ||
| _ = conn.WriteMessage(msgType, payload) | ||
| } | ||
| }, | ||
| } | ||
|
|
||
| r := router.NewRouter(router.RouterConfig{ | ||
| Logger: logger, | ||
| SubRouters: []router.SubRouterConfig{{ | ||
| PathPrefix: "/ws", | ||
| Routes: []router.RouteDefinition{wsRoute}, | ||
| }}, | ||
| }, authFn, userFromUserFn) | ||
| ``` | ||
|
|
||
| The route is registered under the sub-router path prefix (e.g., `/ws/echo`). Only `GET` is used for WebSocket registration because the handshake is defined on `GET`. | ||
|
|
||
| ## Upgrader configuration | ||
|
|
||
| `WebSocketRouteConfig` accepts an optional `Upgrader`. When omitted, a permissive upgrader is used (it allows all origins). Provide a custom `websocket.Upgrader` when you need stricter origin checks or other advanced settings. | ||
|
|
||
| ## Middleware, authentication, and limits | ||
|
|
||
| The router wraps WebSocket routes with the same middleware chain as HTTP routes: | ||
|
|
||
| - Global, sub-router, and route-level middleware are executed before the upgrade occurs. | ||
| - Authentication levels (`AuthRequired`, `AuthOptional`, `NoAuth`) are honored for the handshake request. | ||
| - Timeout, rate limit, and max body size overrides are applied to the handshake phase. For long-lived WebSocket sessions, consider leaving timeouts unset or explicitly set them to `0` for the route. | ||
|
|
||
| ## Shutdown behavior | ||
|
|
||
| During graceful shutdown, SRouter waits for active WebSocket handlers to return before completing shutdown, just like regular HTTP handlers. Your handler should monitor `ctx.Done()` and exit when requested to allow a timely shutdown. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| package router | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "net/http" | ||
|
|
||
| "github.com/Suhaibinator/SRouter/pkg/common" | ||
| "github.com/gorilla/websocket" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| // WebSocketHandler defines the signature for WebSocket route handlers. | ||
| // The request context is passed so callers can respect cancellation or deadlines | ||
| // applied by middleware such as timeouts or shutdown handling. | ||
| type WebSocketHandler func(ctx context.Context, conn *websocket.Conn) | ||
|
|
||
| // WebSocketRouteConfig defines a WebSocket endpoint that can be registered like | ||
| // any other RouteDefinition. | ||
| // | ||
| // Middlewares, authentication, and rate limiting are applied to the handshake | ||
| // request using the existing pipeline so behavior matches standard routes. | ||
| type WebSocketRouteConfig struct { | ||
| Path string | ||
| AuthLevel *AuthLevel | ||
| Overrides common.RouteOverrides | ||
| Middlewares []common.Middleware | ||
| Upgrader *websocket.Upgrader | ||
| Handler WebSocketHandler | ||
| } | ||
|
|
||
| // isRouteDefinition implements the RouteDefinition interface. | ||
| func (WebSocketRouteConfig) isRouteDefinition() {} | ||
|
|
||
| // defaultWebSocketUpgrader returns a lenient upgrader suitable for most tests | ||
| // and local development scenarios. Users can supply their own Upgrader when they | ||
| // need stricter origin checks or advanced configuration. | ||
| func defaultWebSocketUpgrader() *websocket.Upgrader { | ||
| return &websocket.Upgrader{ | ||
| CheckOrigin: func(*http.Request) bool { | ||
| return true | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| // wrapWebSocketHandler creates an http.Handler that performs the WebSocket upgrade | ||
| // before delegating to the provided WebSocketHandler. The handler returned here is | ||
| // still wrapped by the router's middleware chain via wrapHandler. | ||
| func (r *Router[T, U]) wrapWebSocketHandler(route WebSocketRouteConfig) http.HandlerFunc { | ||
| return func(w http.ResponseWriter, req *http.Request) { | ||
| upgrader := route.Upgrader | ||
| if upgrader == nil { | ||
| upgrader = defaultWebSocketUpgrader() | ||
| } | ||
|
|
||
| conn, err := upgrader.Upgrade(w, req, nil) | ||
| if err != nil { | ||
| // If the error is caused by a failed upgrade the upgrader already | ||
| // wrote the appropriate response. Just log and return. | ||
| var closeError *websocket.CloseError | ||
| if errors.As(err, &closeError) { | ||
| r.logger.Debug("WebSocket upgrade closed", zap.Error(err)) | ||
| } else { | ||
| r.logger.Error("WebSocket upgrade failed", zap.Error(err)) | ||
| } | ||
| return | ||
| } | ||
| defer func() { | ||
| if closeErr := conn.Close(); closeErr != nil && !errors.Is(closeErr, websocket.ErrCloseSent) { | ||
| r.logger.Warn("WebSocket close failed", zap.Error(closeErr)) | ||
| } | ||
| }() | ||
|
|
||
| route.Handler(req.Context(), conn) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| package router | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "sync/atomic" | ||
| "testing" | ||
|
|
||
| "github.com/Suhaibinator/SRouter/pkg/common" | ||
| "github.com/Suhaibinator/SRouter/pkg/router/internal/mocks" | ||
| "github.com/gorilla/websocket" | ||
| "github.com/stretchr/testify/require" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| func TestWebSocketRoute(t *testing.T) { | ||
| logger := zap.NewNop() | ||
|
|
||
| middlewareCalled := atomic.Bool{} | ||
|
|
||
| wsRoute := WebSocketRouteConfig{ | ||
| Path: "/echo", | ||
| Middlewares: []common.Middleware{ | ||
| func(next http.Handler) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| middlewareCalled.Store(true) | ||
| next.ServeHTTP(w, r) | ||
| }) | ||
| }, | ||
| }, | ||
| Handler: func(ctx context.Context, conn *websocket.Conn) { | ||
| msgType, data, err := conn.ReadMessage() | ||
| require.NoError(t, err) | ||
| require.NoError(t, conn.WriteMessage(msgType, append([]byte("echo:"), data...))) | ||
| }, | ||
| } | ||
|
|
||
| r := NewRouter(RouterConfig{Logger: logger, SubRouters: []SubRouterConfig{{ | ||
| PathPrefix: "/ws", | ||
| Routes: []RouteDefinition{wsRoute}, | ||
| }}}, mocks.MockAuthFunction, mocks.MockUserIDFromUser) | ||
|
|
||
| server := httptest.NewServer(r) | ||
| defer server.Close() | ||
|
|
||
| wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws/echo" | ||
|
|
||
| conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) | ||
| require.NoError(t, err) | ||
| t.Cleanup(func() { | ||
| _ = conn.Close() | ||
| }) | ||
|
|
||
| require.NoError(t, conn.WriteMessage(websocket.TextMessage, []byte("hello"))) | ||
| _, resp, err := conn.ReadMessage() | ||
| require.NoError(t, err) | ||
| require.Equal(t, "echo:hello", string(resp)) | ||
|
|
||
| require.True(t, middlewareCalled.Load(), "middleware should run before WebSocket handler") | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because WebSocket routes are run through
wrapHandler, any non-zero Global/SubRouter/route timeout adds the timeout middleware, which replaces thehttp.ResponseWriterwithmutexResponseWriterthat does not implementhttp.Hijacker. Thegorilla/websocket.Upgrader.Upgradecall here requires aHijackerand will returnwebsocket: response does not implement http.Hijacker, so WebSocket endpoints cannot upgrade once timeouts (or any similar middleware that wraps the writer) are configured.Useful? React with 👍 / 👎.