diff --git a/doc/design/ext-web-go-rewrite.md b/doc/design/ext-web-go-rewrite.md index 719e7ee..558ef85 100644 --- a/doc/design/ext-web-go-rewrite.md +++ b/doc/design/ext-web-go-rewrite.md @@ -366,12 +366,10 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so | 组件 | 变更 | |------|------| -| 根 `Cargo.toml` workspace | 移除 `plugins/web` Rust member | +| 根 `Cargo.toml` workspace | 移除 `plugins/web` / `web-rust-archive` Rust member | | `tests/gold.rs` | `ensure_web_plugin_built()` → `scripts/build-web-plugin.sh` | +| `marqdo ext add web` | 构建回退:`scripts/build-web-plugin.sh`(Go);Release 仍下发预编译 native zip | | Release 脚本 | Go:`scripts/build-web-plugin.sh`;其它插件仍 `cargo build -p …` | - -| `marqdo ext add web` | 构建回退:有 Go 则 `go build`;Release 仍下发预编译 native zip | -| Release 脚本 | 增加 Go 交叉/本机编译 `libweb` 打包步骤 | | [ext-cli.md](ext-cli.md) / [ext-abi.md](ext-abi.md) | 注明 web 插件实现语言为 Go | ### 9.4 cgo / runtime 注意 @@ -400,7 +398,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so | **W-G10** | proxy + invoke + nested plugin | ✅ `web-proxy-invoke` / hosting live | | **W-G11** | 定制 C2–C4 shell/layout/style/nav | ✅ `web-c2`–`c4` | | **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | ✅ 单测 + `web-g12-api-key-smoke` | -| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线 `tests/ext/web-*`(有 `# main`)全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace | +| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线+live gold(7 个 `*_live`)对 Go 全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace;gold 强制 `MARQDO_WEB_PLUGIN` 避免 `~/.marqdo` 旧 so | | **W-G14** | anlian Marqdo 重写主路径(可分仓或 `examples/anlian-mq/`) | §8 矩阵主路径可演示 | 每波次:**先补 Go 实现 → 跑对应 gold → 再进入下一波**。禁止跨波次留下「注册了但返回 stub 错误」的 ABI(除 W-G0 明确的未实现探测)。 diff --git a/plugins/web/internal/httpx/helpers.go b/plugins/web/internal/httpx/helpers.go new file mode 100644 index 0000000..cbe0df3 --- /dev/null +++ b/plugins/web/internal/httpx/helpers.go @@ -0,0 +1,149 @@ +package httpx + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +func esc(s string) string { + s = strings.ReplaceAll(s, "&", "&") + s = strings.ReplaceAll(s, "<", "<") + s = strings.ReplaceAll(s, ">", ">") + return s +} + +func weakETag(bytes []byte) string { + var h uint64 = 0xcbf29ce484222325 + for _, b := range bytes { + h ^= uint64(b) + h *= 0x0100000001b3 + } + return fmt.Sprintf("W/\"%x-%d\"", h, len(bytes)) +} + +func jsonErr(w http.ResponseWriter, code int, msg string) { + writeJSON(w, code, map[string]any{"ok": false, "error": msg}) +} + +func routeMapOf(appBag map[string]any, key string) map[string]any { + if r, ok := appBag[key].(map[string]any); ok { + return r + } + return map[string]any{} +} + +func routePathKey(path string) string { + p := strings.TrimSpace(path) + if !strings.HasPrefix(p, "/") { + p = "/" + p + } + return p +} + +// goMuxPattern converts Marqdo route patterns (`{*key}`) to Go ServeMux (`{key...}`). +func goMuxPattern(path string) string { + out := path + for { + start := strings.Index(out, "{*") + if start < 0 { + break + } + end := strings.Index(out[start:], "}") + if end < 0 { + break + } + end += start + name := out[start+2 : end] + out = out[:start] + "{" + name + "...}" + out[end+1:] + } + return out +} + +func resolveSession(r *http.Request) (sid, csrf string, setCookie *string) { + cookieHdr := r.Header.Get("Cookie") + id, hadCookie := session.IDFromCookie(cookieHdr) + if hadCookie { + ok := true + if ok && id != "" { + sid = id + if tok, ok := session.CSRFFor(sid); ok { + csrf = tok + } + return sid, csrf, nil + } + } + sid = session.NewID(0) + tok, _ := session.CSRFFor(sid) + c := session.SessionCookie(sid, 0, false) + return sid, tok, &c +} + +func appendSetCookie(w http.ResponseWriter, setCookie *string) { + if setCookie != nil && *setCookie != "" { + w.Header().Add("Set-Cookie", *setCookie) + } +} + +func queryToMap(q string) map[string]any { + out := map[string]any{} + if q == "" { + return out + } + for _, pair := range strings.Split(q, "&") { + if pair == "" { + continue + } + k, v, _ := strings.Cut(pair, "=") + k, _ = url.QueryUnescape(k) + v, _ = url.QueryUnescape(v) + if k != "" { + out[k] = v + } + } + return out +} + +func formToMap(body []byte) map[string]any { + return queryToMap(string(body)) +} + +func jsonWrapInvokeValue(value any) (int, map[string]any, error) { + if value == nil { + return http.StatusInternalServerError, nil, fmt.Errorf("null result") + } + switch t := value.(type) { + case map[string]any: + return http.StatusOK, t, nil + default: + return http.StatusOK, map[string]any{"ok": true, "result": value}, nil + } +} + +func invokeArgsFromPayload(payload map[string]any) map[string]any { + args := map[string]any{} + for k, v := range payload { + args[k] = v + } + if _, ok := args["payload"]; !ok { + args["payload"] = payload + } + return args +} + +func readJSONBody(r *http.Request, max int64) (map[string]any, error) { + r.Body = http.MaxBytesReader(nil, r.Body, max) + defer r.Body.Close() + var raw map[string]any + if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { + return nil, err + } + if raw == nil { + raw = map[string]any{} + } + return raw, nil +} diff --git a/plugins/web/internal/httpx/helpers_test.go b/plugins/web/internal/httpx/helpers_test.go new file mode 100644 index 0000000..0a36ede --- /dev/null +++ b/plugins/web/internal/httpx/helpers_test.go @@ -0,0 +1,12 @@ +package httpx + +import "testing" + +func TestGoMuxPattern(t *testing.T) { + if got := goMuxPattern("/_media/{*key}"); got != "/_media/{key...}" { + t.Fatalf("got %q", got) + } + if got := goMuxPattern("/post/{slug}"); got != "/post/{slug}" { + t.Fatalf("got %q", got) + } +} diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go index 4d5cbdc..3e87abd 100644 --- a/plugins/web/internal/httpx/listen.go +++ b/plugins/web/internal/httpx/listen.go @@ -2,6 +2,7 @@ package httpx import ( + "bufio" "compress/gzip" "encoding/json" "fmt" @@ -16,10 +17,12 @@ import ( "time" "github.com/marqdo/marqdo/plugins/web/internal/app" + "github.com/marqdo/marqdo/plugins/web/internal/assets" "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/form" "github.com/marqdo/marqdo/plugins/web/internal/middleware" "github.com/marqdo/marqdo/plugins/web/internal/render" + "github.com/marqdo/marqdo/plugins/web/internal/sitemap" ) // NewHandler builds the HTTP handler for an app bag (no listen). @@ -59,13 +62,31 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { } mw := middleware.Parse(appBag) + siteHead := assets.HeadLinksFromJSON(appBag["site_head"]) + iconRoutes, err := iconRoutesFromBag(appBag, entryDir, staticDir) + if err != nil { + return nil, err + } st := &state{ - page: page, - dbURL: dbURL, - routes: routes, - forms: forms, - mw: mw, - entryDir: entryDir, + page: page, + dbURL: dbURL, + routes: routes, + forms: forms, + mw: mw, + entryDir: entryDir, + siteHead: siteHead, + iconRoutes: iconRoutes, + redirects: redirectsOf(appBag), + sitemapRoutes: sitemapRoutesOf(appBag), + robotsBody: robotsBodyOf(appBag), + page404: pageOf(appBag, "page_404"), + page500: pageOf(appBag, "page_500"), + uploadRoutes: routeMapOf(appBag, "upload_routes"), + downloadRoutes: routeMapOf(appBag, "download_routes"), + wsRoutes: routeMapOf(appBag, "ws_routes"), + galleryRoutes: routeMapOf(appBag, "gallery_routes"), + proxyRoutes: routeMapOf(appBag, "proxy_routes"), + invokeRoutes: routeMapOf(appBag, "invoke_routes"), } mux := http.NewServeMux() @@ -82,8 +103,8 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { pageV = map[string]any{} } if strings.Contains(routePath, "{") { - mux.HandleFunc("GET "+routePath, st.makeDynamicPage(pageV, routePath)) - mux.HandleFunc("GET "+routePath+"/_part/{id}", st.makeDynamicPart(pageV, routePath)) + mux.HandleFunc("GET "+goMuxPattern(routePath), st.makeDynamicPage(pageV, routePath)) + mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{id}", st.makeDynamicPart(pageV, routePath)) } else { pv := pageV mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) { @@ -112,6 +133,56 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { mux.Handle("HEAD "+staticMount, fs) } + for _, ir := range iconRoutes { + url := ir.URL + path := ir.Path + ct := ir.ContentType + fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct) + mux.HandleFunc("GET "+url, func(w http.ResponseWriter, r *http.Request) { + st.serveIcon(w, path, ct) + }) + mux.HandleFunc("HEAD "+url, func(w http.ResponseWriter, r *http.Request) { + st.serveIcon(w, path, ct) + }) + } + + for _, from := range sortedKeys(st.redirects) { + spec, _ := st.redirects[from].(map[string]any) + to := strOpt(spec, "to", "/") + permanent := boolish(spec["permanent"]) + mux.HandleFunc("GET "+from, func(w http.ResponseWriter, r *http.Request) { + code := http.StatusTemporaryRedirect + if permanent { + code = http.StatusMovedPermanently + } + http.Redirect(w, r, to, code) + }) + } + + for _, path := range sortedKeys(st.sitemapRoutes) { + cfg, _ := st.sitemapRoutes[path].(map[string]any) + mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) { + st.writeSitemap(w, cfg) + }) + } + + if st.robotsBody != "" { + body := st.robotsBody + mux.HandleFunc("GET /robots.txt", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = io.WriteString(w, body) + }) + } + + st.mountWSRoutes(mux) + st.mountUploadRoutes(mux) + st.mountDownloadRoutes(mux) + st.mountGalleryRoutes(mux) + st.mountProxyRoutes(mux) + st.mountInvokeRoutes(mux) + + mux.HandleFunc("/{path...}", st.handleNotFound) + return withMiddleware(mux, mw), nil } @@ -155,12 +226,25 @@ func Listen(appBag map[string]any, entryDir string) (map[string]any, error) { } type state struct { - page map[string]any - dbURL string - routes map[string]any - forms map[string]any - mw middleware.Config - entryDir string + page map[string]any + dbURL string + routes map[string]any + forms map[string]any + mw middleware.Config + entryDir string + siteHead []assets.HeadLink + iconRoutes []assets.IconRoute + redirects map[string]any + sitemapRoutes map[string]any + robotsBody string + page404 map[string]any + page500 map[string]any + uploadRoutes map[string]any + downloadRoutes map[string]any + wsRoutes map[string]any + galleryRoutes map[string]any + proxyRoutes map[string]any + invokeRoutes map[string]any } func (st *state) handleHome(w http.ResponseWriter, r *http.Request) { @@ -171,18 +255,83 @@ func (st *state) handleHomePart(w http.ResponseWriter, r *http.Request) { st.writePart(w, st.page, r.PathValue("id")) } +func (st *state) preparePage(page map[string]any) map[string]any { + p := cloneMap(page) + assets.MergeSiteHead(p, st.siteHead) + return p +} + func (st *state) writePage(w http.ResponseWriter, page map[string]any) { - html := render.RenderPage(page, st.dbURL, "") + html := render.RenderPage(st.preparePage(page), st.dbURL, "") w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, html) } func (st *state) writePart(w http.ResponseWriter, page map[string]any, id string) { - html := render.RenderPage(page, st.dbURL, id) + html := render.RenderPage(st.preparePage(page), st.dbURL, id) w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, html) } +func (st *state) serveIcon(w http.ResponseWriter, path, contentType string) { + data, err := os.ReadFile(path) + if err != nil { + http.NotFound(w, nil) + return + } + w.Header().Set("Content-Type", contentType) + w.Header().Set("Cache-Control", "public, max-age=86400") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) +} + +func (st *state) writeSitemap(w http.ResponseWriter, cfg map[string]any) { + base := strOpt(cfg, "base", "") + items := cfg["items"] + if tbl, ok := cfg["table"].(string); ok && tbl != "" && st.dbURL != "" { + locCol := strOpt(cfg, "loc", "path") + limit := int64(1000) + if n, ok := cfg["limit"].(float64); ok && n > 0 { + limit = int64(n) + } + opts := db.SelectOpts{} + out, err := db.Select(st.dbURL, tbl, limit, opts) + if err == nil { + if rows, ok := out["rows"].([]any); ok { + norm := make([]any, 0, len(rows)) + for _, row := range rows { + m, ok := row.(map[string]any) + if !ok { + continue + } + cp := cloneMap(m) + if _, has := cp["loc"]; !has { + if v, ok := cp[locCol]; ok { + cp["loc"] = v + } + } + norm = append(norm, cp) + } + items = norm + } + } + } + xml := sitemap.BuildSitemap(base, items) + w.Header().Set("Content-Type", "application/xml; charset=utf-8") + _, _ = io.WriteString(w, xml) +} + +func (st *state) handleNotFound(w http.ResponseWriter, r *http.Request) { + if st.page404 != nil { + html := render.RenderPage(st.preparePage(st.page404), st.dbURL, "") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, html) + return + } + http.NotFound(w, r) +} + func (st *state) makeDynamicPage(page map[string]any, pattern string) http.HandlerFunc { paramNames := pathParamNames(pattern) return func(w http.ResponseWriter, r *http.Request) { @@ -280,6 +429,10 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { limit := int64(*mw.BodyLimit) inner := h h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ContentLength > limit { + http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) + return + } r.Body = http.MaxBytesReader(w, r.Body, limit) inner.ServeHTTP(w, r) }) @@ -299,7 +452,7 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { inner.ServeHTTP(w, r) return } - w.Header().Set("Content-Encoding", "gzip") + setHeader(w, "content-encoding", "gzip") w.Header().Add("Vary", "Accept-Encoding") gz := gzip.NewWriter(w) defer gz.Close() @@ -314,7 +467,7 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { val := hv[1] inner := h h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(name, val) + setHeader(w, strings.ToLower(name), val) inner.ServeHTTP(w, r) }) } @@ -346,33 +499,38 @@ func withMiddleware(next http.Handler, mw middleware.Config) http.Handler { func applyCORS(w http.ResponseWriter, r *http.Request, c *middleware.CORSConfig) { origin := r.Header.Get("Origin") if len(c.AllowOrigins) == 0 { - w.Header().Set("Access-Control-Allow-Origin", "*") + setHeader(w, "access-control-allow-origin", "*") } else if origin != "" { for _, o := range c.AllowOrigins { if o == origin { - w.Header().Set("Access-Control-Allow-Origin", origin) + setHeader(w, "access-control-allow-origin", origin) break } } } if len(c.Methods) == 0 { - w.Header().Set("Access-Control-Allow-Methods", "*") + setHeader(w, "access-control-allow-methods", "*") } else { - w.Header().Set("Access-Control-Allow-Methods", strings.Join(unique(c.Methods), ", ")) + setHeader(w, "access-control-allow-methods", strings.Join(unique(c.Methods), ", ")) } if len(c.Headers) == 0 { - w.Header().Set("Access-Control-Allow-Headers", "*") + setHeader(w, "access-control-allow-headers", "*") } else { - w.Header().Set("Access-Control-Allow-Headers", strings.Join(unique(c.Headers), ", ")) + setHeader(w, "access-control-allow-headers", strings.Join(unique(c.Headers), ", ")) } if len(c.ExposeHeaders) > 0 { - w.Header().Set("Access-Control-Expose-Headers", strings.Join(unique(c.ExposeHeaders), ", ")) + expose := strings.ToLower(strings.Join(unique(c.ExposeHeaders), ", ")) + setHeader(w, "access-control-expose-headers", expose) } if c.Credentials { - w.Header().Set("Access-Control-Allow-Credentials", "true") + setHeader(w, "access-control-allow-credentials", "true") } } +func setHeader(w http.ResponseWriter, name, value string) { + w.Header()[name] = []string{value} +} + func securityHeaderName(raw string) (string, bool) { n := strings.ToLower(strings.ReplaceAll(raw, "_", "-")) switch n { @@ -400,6 +558,13 @@ type gzipResponseWriter struct { func (g *gzipResponseWriter) Write(b []byte) (int, error) { return g.w.Write(b) } +func (g *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if h, ok := g.ResponseWriter.(http.Hijacker); ok { + return h.Hijack() + } + return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking") +} + type statusRecorder struct { http.ResponseWriter status int @@ -410,6 +575,13 @@ func (s *statusRecorder) WriteHeader(code int) { s.ResponseWriter.WriteHeader(code) } +func (s *statusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if h, ok := s.ResponseWriter.(http.Hijacker); ok { + return h.Hijack() + } + return nil, nil, fmt.Errorf("underlying ResponseWriter does not support hijacking") +} + func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(code) @@ -540,3 +712,90 @@ func unique(ss []string) []string { } return out } + +func boolish(v any) bool { + switch t := v.(type) { + case bool: + return t + case string: + return t == "true" || t == "True" || t == "1" || t == "yes" + case float64: + return t != 0 + } + return false +} + +func redirectsOf(appBag map[string]any) map[string]any { + if r, ok := appBag["redirects"].(map[string]any); ok { + return r + } + return map[string]any{} +} + +func sitemapRoutesOf(appBag map[string]any) map[string]any { + if r, ok := appBag["sitemap_routes"].(map[string]any); ok { + return r + } + return map[string]any{} +} + +func robotsBodyOf(appBag map[string]any) string { + if s, ok := appBag["robots_body"].(string); ok { + return s + } + return "" +} + +func pageOf(appBag map[string]any, key string) map[string]any { + if p, ok := appBag[key].(map[string]any); ok { + return p + } + return nil +} + +func iconRoutesFromBag(appBag map[string]any, entryDir, staticDir string) ([]assets.IconRoute, error) { + var routes []assets.IconRoute + if icons, ok := appBag["icons"].([]any); ok { + for _, ic := range icons { + m, ok := ic.(map[string]any) + if !ok { + continue + } + p := strOpt(m, "path", "") + url := strOpt(m, "url", "") + if p == "" || url == "" { + continue + } + if !strings.HasPrefix(url, "/") { + return nil, fmt.Errorf("icon url `%s` must start with /", url) + } + abs := resolvePath(p, entryDir) + fi, err := os.Stat(abs) + if err != nil || fi.IsDir() { + return nil, fmt.Errorf("icon file `%s` not found for `%s`", abs, url) + } + ct := strOpt(m, "type", "") + if ct == "" { + ct = assets.MimeForPath(p) + } + routes = append(routes, assets.IconRoute{ + URL: url, Path: abs, ContentType: ct, + }) + } + } + if len(routes) == 0 && staticDir != "" { + for _, name := range []string{"favicon.ico", "favicon.png", "favicon.svg"} { + p := filepath.Join(staticDir, name) + fi, err := os.Stat(p) + if err == nil && !fi.IsDir() { + routes = append(routes, assets.IconRoute{ + URL: "/favicon.ico", + Path: p, + ContentType: assets.MimeForPath(name), + }) + break + } + } + } + return routes, nil +} diff --git a/plugins/web/internal/httpx/listen_test.go b/plugins/web/internal/httpx/listen_test.go index 2dcbe92..19e3705 100644 --- a/plugins/web/internal/httpx/listen_test.go +++ b/plugins/web/internal/httpx/listen_test.go @@ -11,6 +11,7 @@ import ( "github.com/marqdo/marqdo/plugins/web/internal/app" "github.com/marqdo/marqdo/plugins/web/internal/httpx" + "github.com/marqdo/marqdo/plugins/web/internal/middleware" ) func TestNewHandlerHomeRoutesStatic(t *testing.T) { @@ -65,3 +66,86 @@ func TestNewHandlerHomeRoutesStatic(t *testing.T) { } } } + +func TestNewHandlerIconsRedirectSitemap404(t *testing.T) { + dir := t.TempDir() + iconPath := filepath.Join(dir, "favicon.png") + if err := os.WriteFile(iconPath, []byte("PNG"), 0o644); err != nil { + t.Fatal(err) + } + + page := map[string]any{"title": "W7", "intro": "
home
"} + nf := map[string]any{"title": "Not Found Page", "intro": "missing
"} + a := app.New(map[string]any{"page": page}) + a, err := app.Icons(a, []any{ + map[string]any{"path": iconPath, "rel": "icon", "type": "image/png", "url": "/favicon.ico"}, + }) + if err != nil { + t.Fatal(err) + } + a, err = app.Redirect(a, "/legacy", "/", true) + if err != nil { + t.Fatal(err) + } + a, err = app.ErrorPage(a, 404, nf) + if err != nil { + t.Fatal(err) + } + items := []any{map[string]any{"loc": "/"}, map[string]any{"loc": "/about"}} + a, err = app.Sitemap(a, "/sitemap.xml", "http://example.com", "", "path", 100, items) + if err != nil { + t.Fatal(err) + } + a, err = app.Robots(a, "", "http://example.com/sitemap.xml") + if err != nil { + t.Fatal(err) + } + a, err = middleware.Configure(a, map[string]any{"cache_control": "public, max-age=120"}) + if err != nil { + t.Fatal(err) + } + + h, err := httpx.NewHandler(a, dir) + if err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)) + if rec.Code != 200 || !strings.Contains(rec.Header().Get("Content-Type"), "image/") { + t.Fatalf("favicon code=%d ct=%q", rec.Code, rec.Header().Get("Content-Type")) + } + + rec = httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/legacy", nil)) + if rec.Code != http.StatusMovedPermanently { + t.Fatalf("redirect code=%d", rec.Code) + } + + rec = httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/sitemap.xml", nil)) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "No media yet.
" + } + + html := fmt.Sprintf(` + + +