Skip to content

Commit

Permalink
Merge pull request #5 from gwynforthewyn/fix-500-error
Browse files Browse the repository at this point in the history
Fixes 500 error on a request for a directory.
  • Loading branch information
gwynforthewyn committed Apr 1, 2024
2 parents 1c5eebe + f5626a9 commit 1ddecb4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
13 changes: 12 additions & 1 deletion andrew_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,19 @@ func ParseArgs(args []string) (string, string, string) {
func (a AndrewServer) Serve(w http.ResponseWriter, r *http.Request) {
pagePath := path.Clean(r.RequestURI)

if strings.HasSuffix(pagePath, "/") {
// Ensure the pagePath is relative to the root of a.SiteFiles.
// This involves trimming a leading slash if present.
pagePath = strings.TrimPrefix(pagePath, "/")

maybeDir, _ := fs.Stat(a.SiteFiles, pagePath)

switch {
case maybeDir != nil && maybeDir.IsDir():
pagePath = pagePath + "/index.html"
case strings.HasSuffix(pagePath, "/"):
pagePath = pagePath + "index.html"
case pagePath == "":
pagePath = pagePath + "/index.html"
}

if isIndexPage(pagePath) {
Expand Down
39 changes: 39 additions & 0 deletions andrew_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,45 @@ func TestGetPagesWithoutSpecifyingPageDefaultsToIndexHtml(t *testing.T) {
}
}

func TestGettingADirectoryDefaultsToIndexHtml(t *testing.T) {
t.Parallel()

expected := []byte(`
<!DOCTYPE html>
<head>
<title>index title</title>
</head>
<body>
</body>
`)

contentRoot := t.TempDir()
os.MkdirAll(contentRoot+"/pages", 0o755)

// fstest.MapFS does not create directory-like objects, so we need a real file system in this test.
err := os.WriteFile(contentRoot+"/pages/index.html", expected, 0o755)
if err != nil {
t.Fatal(err)
}
testUrl := startAndrewServer(t, os.DirFS(contentRoot))

resp, err := http.Get(testUrl + "/pages/")

if err != nil {
t.Fatal(err)
}

received, err := io.ReadAll(resp.Body)

if err != nil {
t.Fatal(err)
}

if !slices.Equal(received, expected) {
t.Fatalf("Expected %q, received %q", expected, received)
}
}

func TestGetPagesCanRetrieveOtherPages(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 1ddecb4

Please sign in to comment.