Serve the index page for an empty URL path instead of panicking (closes #149) #165
@@ -0,0 +1,12 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import "github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
// NewTestSPAServer creates a Server whose router serves only
|
||||||
|
// the embedded web client.
|
||||||
|
func NewTestSPAServer() *Server {
|
||||||
|
srv := &Server{router: chi.NewRouter()}
|
||||||
|
srv.setupSPA()
|
||||||
|
|
||||||
|
return srv
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package server
|
|||||||
import (
|
import (
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"sneak.berlin/go/neoirc/web"
|
"sneak.berlin/go/neoirc/web"
|
||||||
@@ -137,8 +138,10 @@ func (srv *Server) setupSPA() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The path is empty, not "/", for a request line such
|
||||||
|
// as "GET http://host HTTP/1.1".
|
||||||
fileData, readErr := readFS.ReadFile(
|
fileData, readErr := readFS.ReadFile(
|
||||||
request.URL.Path[1:],
|
strings.TrimPrefix(request.URL.Path, "/"),
|
||||||
)
|
)
|
||||||
if readErr != nil || len(fileData) == 0 {
|
if readErr != nil || len(fileData) == 0 {
|
||||||
indexHTML, indexErr := readFS.ReadFile(
|
indexHTML, indexErr := readFS.ReadFile(
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package server_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"sneak.berlin/go/neoirc/internal/server"
|
||||||
|
"sneak.berlin/go/neoirc/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// An absolute-form request line with no path, such as
|
||||||
|
// "GET http://example.com HTTP/1.1", leaves URL.Path empty.
|
||||||
|
func TestSPAServesIndexForEmptyPath(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
request := httptest.NewRequestWithContext(
|
||||||
|
t.Context(), http.MethodGet, "http://example.com", nil,
|
||||||
|
)
|
||||||
|
if request.URL.Path != "" {
|
||||||
|
t.Fatalf("URL.Path is %q, want it empty", request.URL.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
|
||||||
|
server.NewTestSPAServer().ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status %d, want %d", recorder.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
indexHTML, err := fs.ReadFile(web.Dist, "dist/index.html")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if recorder.Body.String() != string(indexHTML) {
|
||||||
|
t.Errorf("body is not the index page")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user