1 parent
ffbf603bc8
commit
4de0a01464
6 files changed
+87
-44
No files matched your search
@@ -7,7 +7,7 @@ let gameState = {
|
||||
isLocked: false,
|
||||
polling: false,
|
||||
pollController: null,
|
||||
apiUrl: '',
|
||||
apiUrl: apiBase(document.currentScript),
|
||||
selectedSquare: null,
|
||||
healthCheckInterval: null,
|
||||
networkError: false,
|
||||
@@ -49,10 +49,7 @@ function clearModalMessage(elementId) {
|
||||
}
|
||||
|
||||
// Initialize on page load
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const config = await getConfig();
|
||||
gameState.apiUrl = config.apiUrl;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Check for existing session on load
|
||||
restoreAuthSession();
|
||||
|
||||
@@ -471,21 +468,14 @@ function authFetch(url, options = {}) {
|
||||
return fetch(url, options);
|
||||
}
|
||||
|
||||
async function getConfig() {
|
||||
try {
|
||||
const response = await fetch('./config', { cache: 'no-store' });
|
||||
if (!response.ok) throw new Error(`config returned ${response.status}`);
|
||||
const config = await response.json();
|
||||
if (typeof config.apiUrl !== 'string' || !config.apiUrl.trim()) {
|
||||
throw new Error('config is missing apiUrl');
|
||||
}
|
||||
return { apiUrl: config.apiUrl.replace(/\/+$/, '') };
|
||||
} catch (error) {
|
||||
// Static production hosting currently reverse-proxies the API here.
|
||||
// The embedded server supplies /config and does not use this fallback.
|
||||
console.debug('Using default API route:', error.message);
|
||||
return { apiUrl: '/chess' };
|
||||
}
|
||||
// The API base, from the page that loads this script: its element's data-api,
|
||||
// set by the embedded server from -web-api-url and by a host that publishes
|
||||
// the files itself. Without it, /chess, where a static host proxies the API.
|
||||
// "/" is the origin's root. Read while the script runs: document.currentScript
|
||||
// is null in any callback.
|
||||
function apiBase(script) {
|
||||
const api = script?.dataset.api?.trim();
|
||||
return api ? api.replace(/\/+$/, '') : '/chess';
|
||||
}
|
||||
|
||||
function startHealthCheck() {
|
||||
|
||||
@@ -3,6 +3,7 @@ package webserver
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"html"
|
||||
"io/fs"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -39,36 +40,30 @@ func Start(host string, port int, apiURL string, logRequests bool) error {
|
||||
return fmt.Errorf("failed to create web sub-filesystem: %w", err)
|
||||
}
|
||||
|
||||
// API config endpoint, served before the static file handler
|
||||
app.Get("/config", func(c *fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"apiUrl": apiURL,
|
||||
})
|
||||
})
|
||||
index, err := indexHTML(webContent, apiURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Serve static files from the embedded client directory.
|
||||
app.Get("*", func(c *fiber.Ctx) error {
|
||||
path := c.Path()
|
||||
|
||||
// Default to index.html for the root path
|
||||
if path == "/" {
|
||||
path = "/index.html"
|
||||
}
|
||||
|
||||
// The path for the embedded filesystem must not have a leading slash
|
||||
fsPath := strings.TrimPrefix(path, "/")
|
||||
fsPath := strings.TrimPrefix(c.Path(), "/")
|
||||
|
||||
sendIndex := func() error {
|
||||
c.Set("Content-Type", "text/html; charset=utf-8")
|
||||
return c.Send(index)
|
||||
}
|
||||
if fsPath == "" || fsPath == "index.html" {
|
||||
return sendIndex()
|
||||
}
|
||||
|
||||
// Try to read the file
|
||||
data, err := fs.ReadFile(webContent, fsPath)
|
||||
if err != nil {
|
||||
// If the file isn't found, serve index.html for SPA-style routing
|
||||
// This handles client-side routes that don't correspond to a file
|
||||
data, err = fs.ReadFile(webContent, "index.html")
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).SendString("index.html not found")
|
||||
}
|
||||
c.Set("Content-Type", "text/html; charset=utf-8")
|
||||
return c.Send(data)
|
||||
return sendIndex()
|
||||
}
|
||||
|
||||
// Set the correct Content-Type based on file extension
|
||||
@@ -89,3 +84,22 @@ func Start(host string, port int, apiURL string, logRequests bool) error {
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
return app.Listen(addr)
|
||||
}
|
||||
|
||||
// boardScript is how index.html loads the board; indexHTML adds the API base.
|
||||
const boardScript = `<script src="app.js">`
|
||||
|
||||
// indexHTML returns the client's index.html with the browser-visible API base
|
||||
// on the board's script element, data-api, which app.js reads as it runs: the
|
||||
// same attribute a host that publishes the files itself sets.
|
||||
func indexHTML(content fs.FS, apiURL string) ([]byte, error) {
|
||||
data, err := fs.ReadFile(content, "index.html")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("embedded index.html: %w", err)
|
||||
}
|
||||
page := string(data)
|
||||
if n := strings.Count(page, boardScript); n != 1 {
|
||||
return nil, fmt.Errorf("embedded index.html has %s %d times, want once", boardScript, n)
|
||||
}
|
||||
tag := fmt.Sprintf(`<script src="app.js" data-api="%s">`, html.EscapeString(apiURL))
|
||||
return []byte(strings.Replace(page, boardScript, tag, 1)), nil
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package webserver
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func TestEmbeddedWebClientRoot(t *testing.T) {
|
||||
@@ -20,3 +22,37 @@ func TestEmbeddedWebClientRoot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexHTMLSetsAPIBase(t *testing.T) {
|
||||
content, err := fs.Sub(webFS, "chess-client-web")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for apiURL, want := range map[string]string{
|
||||
"http://localhost:8080": `<script src="app.js" data-api="http://localhost:8080">`,
|
||||
`https://x.test/?a=1&b="2"`: `<script src="app.js" data-api="https://x.test/?a=1&b="2"">`,
|
||||
} {
|
||||
page, err := indexHTML(content, apiURL)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", apiURL, err)
|
||||
}
|
||||
if n := strings.Count(string(page), want); n != 1 {
|
||||
t.Errorf("%s: index.html has %s %d times, want once", apiURL, want, n)
|
||||
}
|
||||
if strings.Contains(string(page), boardScript) {
|
||||
t.Errorf("%s: index.html still loads the board without data-api", apiURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexHTMLRefusesChangedScript(t *testing.T) {
|
||||
for name, page := range map[string]string{
|
||||
"absent": `<script src="./app.js"></script>`,
|
||||
"twice": `<script src="app.js"></script><script src="app.js"></script>`,
|
||||
} {
|
||||
content := fstest.MapFS{"index.html": {Data: []byte(page)}}
|
||||
if _, err := indexHTML(content, "http://localhost:8080"); err == nil {
|
||||
t.Errorf("%s: no error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user