Download
64 lines 2.1 KiBGoModified 2026-10-27 raw
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
package main

import (
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
)

func TestHandler(t *testing.T) {
	pub, priv := t.TempDir(), t.TempDir()
	for root, files := range map[string]map[string]string{
		pub: {
			"index.html": "index", "code/proj.html": "root page", "code/proj/src.html": "src page",
			"code/proj/src/main.c.html": "main.c page", "code/proj/d/index.html": "index page",
			"code/proj/foo.html.html": "foo.html page", "types/proj/code/c.html": "c files",
			"search/proj/index.html": "search", "raw/proj/src/main.c": "int main;", "static/style.css": "css",
		},
		priv: {"private/index.html": "private index", "private/code/secret.html": "secret page"},
	} {
		for name, body := range files {
			p := filepath.Join(root, filepath.FromSlash(name))
			if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
				t.Fatal(err)
			}
			if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
				t.Fatal(err)
			}
		}
	}
	for _, private := range []string{priv, ""} {
		srv := httptest.NewServer(handler(pub, private))
		for u, want := range map[string]string{
			"/": "index", "/code/proj": "root page", "/code/proj/": "root page", "/code/proj/src": "src page",
			"/code/proj/src/": "src page", "/code/proj/src/main.c": "main.c page", "/code/proj/d/index": "index page",
			"/code/proj/foo.html": "foo.html page", "/types/proj/code/c": "c files", "/search/proj/": "search",
			"/raw/proj/src/main.c": "int main;", "/static/style.css": "css",
			"/private/": "private index", "/private/code/secret": "secret page",
		} {
			if private == "" && u[:min(len(u), 9)] == "/private/" {
				want = ""
			}
			res, err := http.Get(srv.URL + u)
			if err != nil {
				t.Fatal(err)
			}
			b, err := io.ReadAll(res.Body)
			_ = res.Body.Close() // read to the end above
			if err != nil {
				t.Fatal(err)
			}
			if want == "" {
				if res.StatusCode != http.StatusNotFound {
					t.Errorf("GET %s with no private site: %d", u, res.StatusCode)
				}
			} else if res.StatusCode != http.StatusOK || string(b) != want {
				t.Errorf("GET %s: %d %q, want %q", u, res.StatusCode, b, want)
			}
		}
		srv.Close()
	}
}