feat: add standalone themed error pages
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// The generated page needs no API calls and preserves the actual failure status.
|
||||
func (a *App) errorPage(w http.ResponseWriter, r *http.Request, status int) {
|
||||
raw, err := os.ReadFile(filepath.Join(a.cfg.Static, "errors", strconv.Itoa(status)+".html"))
|
||||
if err != nil {
|
||||
http.Error(w, http.StatusText(status), status)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
if r.Method != http.MethodHead {
|
||||
w.Write(raw)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) servePageFile(w http.ResponseWriter, r *http.Request, path string) {
|
||||
info, err := os.Stat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
a.errorPage(w, r, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, os.ErrPermission) || (err == nil && info.IsDir()) {
|
||||
a.errorPage(w, r, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Printf("file unavailable: %v", err)
|
||||
a.errorPage(w, r, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, path)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStyledBrowserErrorsRetainStatusAndAPIJSON(t *testing.T) {
|
||||
c := fixture(t)
|
||||
dir := filepath.Join(c.app.cfg.Static, "errors")
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, code := range []int{403, 404, 405, 500, 502, 503, 504} {
|
||||
html := fmt.Sprintf("<!doctype html><title>MirrorITS %d</title><h1>%d</h1>", code, code)
|
||||
if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%d.html", code)), []byte(html), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, method := range []string{"GET", "HEAD"} {
|
||||
w := httptest.NewRecorder()
|
||||
c.app.errorPage(w, httptest.NewRequest(method, "/missing?code=200", nil), code)
|
||||
if w.Code != code || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") || w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("error response lost status or headers: %+v", w)
|
||||
}
|
||||
if method == "HEAD" && w.Body.Len() != 0 {
|
||||
t.Fatal("HEAD error includes a body")
|
||||
}
|
||||
if method == "GET" && w.Body.String() != html {
|
||||
t.Fatal("error response did not use the static page")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/missing-page", "/assets/missing.js", "/uploads/missing.png", "/uploads/mirrorouc.db"} {
|
||||
w := c.call("GET", path, nil, false)
|
||||
status(t, w, 404)
|
||||
if !strings.Contains(w.Body.String(), "MirrorITS 404") {
|
||||
t.Fatalf("default browser error remains at %s", path)
|
||||
}
|
||||
}
|
||||
w := c.call("POST", "/missing-page", nil, false)
|
||||
status(t, w, 405)
|
||||
if w.Header().Get("Allow") != "GET, HEAD" {
|
||||
t.Fatal("Allow header was lost")
|
||||
}
|
||||
for _, path := range []string{"/api/missing", "/api/v1/help/missing"} {
|
||||
w = c.call("GET", path, nil, false)
|
||||
status(t, w, 404)
|
||||
if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") || !strings.Contains(w.Body.String(), `"NOT_FOUND"`) {
|
||||
t.Fatal("API error changed to an HTML page")
|
||||
}
|
||||
}
|
||||
// Healthy assets still support byte ranges through the ordinary file server.
|
||||
assets := filepath.Join(c.app.cfg.Static, "assets")
|
||||
os.MkdirAll(assets, 0700)
|
||||
os.WriteFile(filepath.Join(assets, "sample.txt"), []byte("0123456789"), 0600)
|
||||
r := httptest.NewRequest("GET", "/assets/sample.txt", nil)
|
||||
r.Header.Set("Range", "bytes=2-5")
|
||||
response := httptest.NewRecorder()
|
||||
c.app.handler().ServeHTTP(response, r)
|
||||
if response.Code != http.StatusPartialContent || response.Body.String() != "2345" {
|
||||
t.Fatal("error pages changed healthy file range handling")
|
||||
}
|
||||
}
|
||||
+16
-7
@@ -131,15 +131,15 @@ func (a *App) handler() http.Handler {
|
||||
mux.HandleFunc("GET /uploads/{name}", func(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
if !validName(name) || (!strings.HasSuffix(name, ".png") && !strings.HasSuffix(name, ".jpg")) {
|
||||
http.NotFound(w, r)
|
||||
a.errorPage(w, r, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
http.ServeFile(w, r, filepath.Join(a.cfg.Data, "uploads", name))
|
||||
a.servePageFile(w, r, filepath.Join(a.cfg.Data, "uploads", name))
|
||||
})
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "GET" && r.Method != "HEAD" {
|
||||
w.Header().Set("Allow", "GET, HEAD")
|
||||
fail(w, 405, "METHOD_NOT_ALLOWED")
|
||||
a.errorPage(w, r, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
path := r.URL.Path
|
||||
@@ -148,20 +148,29 @@ func (a *App) handler() http.Handler {
|
||||
return
|
||||
}
|
||||
if path == "/" || path == "/status" || path == "/status/" || path == "/announcements" || path == "/announcements/" || path == "/admin" || strings.HasPrefix(path, "/admin/") {
|
||||
http.ServeFile(w, r, filepath.Join(a.cfg.Static, "index.html"))
|
||||
a.servePageFile(w, r, filepath.Join(a.cfg.Static, "index.html"))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(path, "/assets/") {
|
||||
http.FileServer(http.Dir(a.cfg.Static)).ServeHTTP(w, r)
|
||||
local := strings.TrimPrefix(path, "/")
|
||||
if !filepath.IsLocal(local) || strings.ContainsAny(local, "\\\x00") {
|
||||
a.errorPage(w, r, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
a.servePageFile(w, r, filepath.Join(a.cfg.Static, local))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
a.errorPage(w, r, http.StatusNotFound)
|
||||
})
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if v := recover(); v != nil {
|
||||
a.logger.Printf("panic: %v", v)
|
||||
fail(w, 500, "INTERNAL_ERROR")
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") || r.URL.Path == "/healthz" {
|
||||
fail(w, 500, "INTERNAL_ERROR")
|
||||
} else {
|
||||
a.errorPage(w, r, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}()
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
|
||||
Reference in New Issue
Block a user