From fd9c930c28b928ea3a0fb4e5537d7d2b6de23aad Mon Sep 17 00:00:00 2001 From: James Harris Date: Mon, 1 Jul 2024 08:36:29 +1000 Subject: [PATCH] Serve `.ws` and `.sse` under any path. --- README.md | 9 ++------- cmd/echo-server/main.go | 11 ++++++----- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 3e3b51a..f75f614 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,8 @@ information about HTTP request headers and bodies back to the client. ## Behavior - Any messages sent from a websocket client are echoed as a websocket message. -- Visit `/.ws` in a browser for a basic UI to connect and send websocket messages. -- Request `/.sse` to receive the echo response via server-sent events. +- Requests to a file named `.ws` under any path serve a basic UI to connect and send websocket messages. +- Requests to a file named `.sse` under any path streams server-sent events. - Request any other URL to receive the echo response in plain text. ## Configuration @@ -45,11 +45,6 @@ SEND_HEADER_ACCESS_CONTROL_ALLOW_METHODS="*" SEND_HEADER_ACCESS_CONTROL_ALLOW_HEADERS="*" ``` -### Web Socket Test Path - -Set the `FRONTEND_WS_PATH` environment variable to send web socket request to the particular path -instead of root - ## Running the server The examples below show a few different ways of running the server with the HTTP diff --git a/cmd/echo-server/main.go b/cmd/echo-server/main.go index 398a1e7..4e1a83e 100644 --- a/cmd/echo-server/main.go +++ b/cmd/echo-server/main.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "os" + "path" "sort" "strconv" "strings" @@ -101,9 +102,9 @@ func handler(wr http.ResponseWriter, req *http.Request) { if websocket.IsWebSocketUpgrade(req) { serveWebSocket(wr, req, sendServerHostname) - } else if req.URL.Path == "/.ws" { - serveFrontend(wr) - } else if req.URL.Path == "/.sse" { + } else if path.Base(req.URL.Path) == ".ws" { + serveFrontend(wr, req) + } else if path.Base(req.URL.Path) == ".sse" { serveSSE(wr, req, sendServerHostname) } else { serveHTTP(wr, req, sendServerHostname) @@ -162,7 +163,7 @@ func serveWebSocket(wr http.ResponseWriter, req *http.Request, sendServerHostnam //go:embed "html" var files embed.FS -func serveFrontend(wr http.ResponseWriter) { +func serveFrontend(wr http.ResponseWriter, req *http.Request) { const templateName = "html/frontend.tmpl.html" tmpl, err := template.ParseFS(files, templateName) if err != nil { @@ -172,7 +173,7 @@ func serveFrontend(wr http.ResponseWriter) { templateData := struct { Path string }{ - Path: os.Getenv("FRONTEND_WS_PATH"), + Path: path.Dir(req.URL.Path), } err = tmpl.Execute(wr, templateData) if err != nil {