package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
func writeConfig(t *testing.T, host string) string {
t.Helper()
file := filepath.Join(t.TempDir(), "config.yaml")
data := fmt.Sprintf("host: %s\nmodules:\n tool:\n repo: https://example.com/%s\n subdir: cmd/tool\n", host, host)
if err := os.WriteFile(file, []byte(data), 0600); err != nil {
t.Fatal(err)
}
return file
}
func TestServerResponses(t *testing.T) {
config := Config{configPath: writeConfig(t, "go.example.com"), templateDir: "templates"}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
for _, tc := range []struct {
path string
status int
want string
}{
{"/", http.StatusOK, `https://example.com/go.example.com`},
{"/", http.StatusOK, `go.example.com/tool`},
{"/tool?go-get=1", http.StatusOK, `content="go.example.com/tool git https://example.com/go.example.com cmd/tool"`},
{"/tool/pkg/nested?go-get=1", http.StatusOK, `content="go.example.com/tool git https://example.com/go.example.com cmd/tool"`},
{"/toolbox", http.StatusNotFound, "404"},
{"/toolbox?go-get=1", http.StatusNotFound, "404"},
} {
t.Run(tc.path, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, tc.path, nil)
w := httptest.NewRecorder()
if r.URL.Path == "/" {
server.Index(w, r)
} else {
server.Fallback(w, r)
}
if w.Code != tc.status || !strings.Contains(w.Body.String(), tc.want) {
t.Fatalf("status=%d body=%s; want status=%d containing %q", w.Code, w.Body.String(), tc.status, tc.want)
}
})
}
}
func TestModuleVCS(t *testing.T) {
file := filepath.Join(t.TempDir(), "config.yaml")
config := Config{configPath: file, templateDir: "templates"}
server := Server{config: &config}
for _, tc := range []struct {
name string
field string
want string
}{
{"explicit", " vcs: hg\n", "hg"},
{"omitted", "", "git"},
{"empty", " vcs: ''\n", "git"},
{"git", " vcs: git\n", "git"},
} {
t.Run(tc.name, func(t *testing.T) {
data := "host: go.example.com\nmodules:\n tool:\n repo: https://example.com/tool\n" + tc.field
if err := os.WriteFile(file, []byte(data), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest(http.MethodGet, "/tool?go-get=1", nil))
want := fmt.Sprintf(`content="go.example.com/tool %s https://example.com/tool"`, tc.want)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), want) {
t.Fatalf("status=%d body=%s; want %q", w.Code, w.Body.String(), want)
}
})
}
}
func TestModulePageWithoutDiscoveryQuery(t *testing.T) {
config := Config{configPath: writeConfig(t, "go.example.com"), templateDir: "templates"}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
for _, requestPath := range []string{"/tool", "/tool/pkg/nested", "/tool?go-get=0", "/tool?go-get=", "/tool?other=1"} {
t.Run(requestPath, func(t *testing.T) {
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest(http.MethodGet, requestPath, nil))
if w.Code != http.StatusOK || w.Header().Get("Location") != "" {
t.Fatalf("status=%d location=%q", w.Code, w.Header().Get("Location"))
}
for _, want := range []string{
`content="go.example.com/tool git https://example.com/go.example.com cmd/tool"`,
"go get go.example.com/tool",
``,
} {
if !strings.Contains(w.Body.String(), want) {
t.Fatalf("body=%s; want %q", w.Body.String(), want)
}
}
})
}
}
func TestReloadKeepsLastGoodConfiguration(t *testing.T) {
file := writeConfig(t, "go.example.com")
config := Config{configPath: file, templateDir: copyTemplates(t)}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
before := config.current.Load()
override := filepath.Join(config.templateDir, "mod.html")
if err := os.WriteFile(override, []byte("{{"), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err == nil {
t.Fatal("expected invalid template to fail")
}
if config.current.Load() != before {
t.Fatal("failed reload replaced live configuration")
}
if err := os.WriteFile(override, []byte("module={{.Module}}"), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
server := Server{config: &config}
server.Fallback(w, httptest.NewRequest(http.MethodGet, "/tool?go-get=1", nil))
if w.Body.String() != "module=go.example.com/tool" {
t.Fatalf("override not used: %s", w.Body.String())
}
}
func TestTemplateExecutionFailureReturns500(t *testing.T) {
file := writeConfig(t, "go.example.com")
templateDir := copyTemplates(t)
if err := os.WriteFile(filepath.Join(templateDir, "mod.html"), []byte("partial {{.Missing}}"), 0600); err != nil {
t.Fatal(err)
}
config := Config{configPath: file, templateDir: templateDir}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest(http.MethodGet, "/tool?go-get=1", nil))
if w.Code != http.StatusInternalServerError || strings.Contains(w.Body.String(), "partial") {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
}
func TestConcurrentReloadAndRequests(t *testing.T) {
files := []string{writeConfig(t, "one.example.com"), writeConfig(t, "two.example.com")}
config := Config{configPath: writeConfig(t, "one.example.com"), templateDir: "templates"}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
var wg sync.WaitGroup
wg.Go(func() {
for i := range 40 {
data, err := os.ReadFile(files[i%2])
if err != nil {
t.Error(err)
return
}
if err := os.WriteFile(config.configPath, data, 0600); err != nil {
t.Error(err)
return
}
if err := config.Reload(); err != nil {
t.Error(err)
return
}
}
})
for range 4 {
wg.Go(func() {
for range 80 {
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest(http.MethodGet, "/tool/pkg?go-get=1", nil))
body := w.Body.String()
valid := false
for _, host := range []string{"one.example.com", "two.example.com"} {
if strings.Contains(body, fmt.Sprintf(`content="%s/tool git https://example.com/%s cmd/tool"`, host, host)) {
valid = true
}
}
if w.Code != http.StatusOK || !valid {
t.Errorf("inconsistent response: status=%d body=%s", w.Code, body)
return
}
}
})
}
wg.Wait()
}
func TestStaticFallback(t *testing.T) {
config := Config{configPath: writeConfig(t, "go.example.com"), templateDir: "templates"}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
dir := t.TempDir()
for _, name := range []string{"style.css", "index.html", "tool", "error.html"} {
if err := os.WriteFile(filepath.Join(dir, name), []byte("static "+name), 0600); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(filepath.Join(dir, "assets"), 0700); err != nil {
t.Fatal(err)
}
server := Server{config: &config, static: http.Dir(dir)}
mux := http.NewServeMux()
mux.HandleFunc("/{$}", server.Index)
mux.HandleFunc("/", server.Fallback)
for _, tc := range []struct {
path, method string
status int
want string
}{
{"/", "GET", 200, "Go modules"},
{"/tool", "GET", 200, "go.example.com/tool"},
{"/tool/pkg", "GET", 200, "go.example.com/tool"},
{"/style.css", "GET", 200, "static style.css"},
{"/index.html", "GET", 200, "static index.html"},
{"/style.css", "HEAD", 200, ""},
{"/missing", "GET", 404, "404"},
{"/assets/", "GET", 404, "404"},
} {
t.Run(tc.method+tc.path, func(t *testing.T) {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
if w.Code != tc.status || !strings.Contains(w.Body.String(), tc.want) {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if tc.method == "HEAD" && w.Body.Len() != 0 {
t.Fatal("HEAD response has a body")
}
})
}
if err := os.WriteFile(filepath.Join(dir, "style.css"), []byte("updated"), 0600); err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/style.css", nil))
if w.Body.String() != "updated" {
t.Fatalf("static update not served: %s", w.Body.String())
}
}
func copyTemplates(t *testing.T) string {
t.Helper()
dir := t.TempDir()
for _, name := range []string{"index.html", "mod.html", "error.html"} {
data, err := os.ReadFile(filepath.Join("templates", name))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil {
t.Fatal(err)
}
}
return dir
}
func TestReloadFallsBackToDefaultTemplates(t *testing.T) {
file := writeConfig(t, "go.example.com")
config := Config{configPath: file, templateDir: t.TempDir()}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
w := httptest.NewRecorder()
server.Index(w, httptest.NewRequest("GET", "/", nil))
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Go modules") {
t.Fatalf("default index: status=%d body=%s", w.Code, w.Body.String())
}
if err := os.Remove(config.templateDir); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatalf("missing template directory should use defaults: %v", err)
}
if err := os.Mkdir(config.templateDir, 0700); err != nil {
t.Fatal(err)
}
custom := filepath.Join(config.templateDir, "mod.html")
if err := os.WriteFile(custom, []byte("custom {{.Module}}"), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
w = httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest("GET", "/tool", nil))
if w.Body.String() != "custom go.example.com/tool" {
t.Fatalf("custom module: %s", w.Body.String())
}
w = httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest("GET", "/missing", nil))
if w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "404") {
t.Fatalf("default 404: status=%d body=%s", w.Code, w.Body.String())
}
if err := os.Remove(custom); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
w = httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest("GET", "/tool", nil))
if strings.Contains(w.Body.String(), "custom ") || !strings.Contains(w.Body.String(), "go get go.example.com/tool") {
t.Fatalf("removed override did not restore default: %s", w.Body.String())
}
}
type failingStaticFS struct {
file http.File
err error
}
func (f failingStaticFS) Open(string) (http.File, error) { return f.file, f.err }
type failingStatFile struct {
http.File
err error
closed bool
}
func (f *failingStatFile) Stat() (os.FileInfo, error) { return nil, f.err }
func (f *failingStatFile) Close() error { f.closed = true; return nil }
func TestStaticFileErrors(t *testing.T) {
config := Config{configPath: writeConfig(t, "go.example.com"), templateDir: "templates"}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
err error
status int
}{
{"missing", os.ErrNotExist, http.StatusNotFound},
{"permission", os.ErrPermission, http.StatusInternalServerError},
{"io", io.ErrUnexpectedEOF, http.StatusInternalServerError},
} {
for _, stat := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/stat=%t", tc.name, stat), func(t *testing.T) {
static := failingStaticFS{err: tc.err}
file := &failingStatFile{err: tc.err}
if stat {
static = failingStaticFS{file: file}
}
server := Server{config: &config, static: static}
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest("GET", "/asset.css", nil))
if w.Code != tc.status {
t.Fatalf("status=%d; want %d", w.Code, tc.status)
}
if tc.status == http.StatusInternalServerError && !strings.Contains(w.Body.String(), "500 — Internal Server Error") {
t.Fatalf("unexpected error response: %q", w.Body.String())
}
if stat && !file.closed {
t.Fatal("file was not closed after stat failed")
}
})
}
}
}
func TestCustomErrorTemplate(t *testing.T) {
config := Config{configPath: writeConfig(t, "go.example.com"), templateDir: t.TempDir()}
if err := os.WriteFile(filepath.Join(config.templateDir, "error.html"), []byte("{{.Code}}: {{.Message}}"), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
static http.FileSystem
status int
}{
{nil, http.StatusNotFound},
{failingStaticFS{err: os.ErrPermission}, http.StatusInternalServerError},
} {
server := Server{config: &config, static: tc.static}
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest("GET", "/missing", nil))
want := fmt.Sprintf("%d: %s", tc.status, http.StatusText(tc.status))
if w.Code != tc.status || w.Body.String() != want {
t.Fatalf("status=%d body=%q; want %d %q", w.Code, w.Body.String(), tc.status, want)
}
}
}
func TestErrorTemplateFailureReturnsPlain500(t *testing.T) {
config := Config{configPath: writeConfig(t, "go.example.com"), templateDir: t.TempDir()}
if err := os.WriteFile(filepath.Join(config.templateDir, "error.html"), []byte("partial {{.Missing}}"), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
w := httptest.NewRecorder()
server.Fallback(w, httptest.NewRequest("GET", "/missing", nil))
if w.Code != http.StatusInternalServerError || w.Body.String() != "Internal Server Error\n" {
t.Fatalf("status=%d body=%q", w.Code, w.Body.String())
}
}
func TestIndexAlphabeticalOrder(t *testing.T) {
config := Config{configPath: filepath.Join(t.TempDir(), "config.yaml"), templateDir: t.TempDir()}
if err := os.WriteFile(filepath.Join(config.templateDir, "index.html"), []byte("{{range .Modules}}{{.Path}} {{else}}empty{{end}}"), 0600); err != nil {
t.Fatal(err)
}
server := Server{config: &config}
for _, tc := range []struct {
yaml string
want string
}{
{"modules:\n text: {}\n net: {}\n example/tools: {}\n example: {}\n sync: {}\n", "/example /example/tools /net /sync /text "},
{"modules:\n zebra: {}\n alpha: {}\n", "/alpha /zebra "},
{"modules: {}\n", "empty"},
} {
if err := os.WriteFile(config.configPath, []byte(tc.yaml), 0600); err != nil {
t.Fatal(err)
}
if err := config.Reload(); err != nil {
t.Fatal(err)
}
for range 10 {
w := httptest.NewRecorder()
server.Index(w, httptest.NewRequest("GET", "/", nil))
if w.Code != http.StatusOK || w.Body.String() != tc.want {
t.Fatalf("status=%d body=%q; want %q", w.Code, w.Body.String(), tc.want)
}
}
}
}