fix(site): 按 Host 注入租户标题与 SEO 信息
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
package storefrontshell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type shellProvider interface {
|
||||
Get(ctx context.Context) ([]byte, error)
|
||||
}
|
||||
|
||||
// Handler serves the SPA shell for extensionless document requests. Caddy
|
||||
// routes only HTML document paths here; API and static asset paths stay on
|
||||
// their existing handlers.
|
||||
type Handler struct {
|
||||
provider shellProvider
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
func NewHandler(provider shellProvider, logger *zap.Logger) *Handler {
|
||||
return &Handler{provider: provider, logger: logger}
|
||||
}
|
||||
|
||||
func (h *Handler) Serve(c *gin.Context) {
|
||||
if h == nil || h.provider == nil || !IsDocumentPath(c.Request.URL.Path) {
|
||||
response.NotFound(c, "页面不存在")
|
||||
return
|
||||
}
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
response.NotFound(c, "页面不存在")
|
||||
return
|
||||
}
|
||||
|
||||
shell, err := h.provider.Get(c.Request.Context())
|
||||
if err != nil {
|
||||
if h.logger != nil {
|
||||
h.logger.Error("读取前台 HTML 模板失败", zap.Error(err))
|
||||
}
|
||||
writeUnavailable(c)
|
||||
return
|
||||
}
|
||||
|
||||
meta := MetaFromRequest(c)
|
||||
page := Inject(shell, meta)
|
||||
etag := ETag(meta, shell)
|
||||
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
c.Header("Vary", "Host")
|
||||
c.Header("ETag", etag)
|
||||
if etagMatches(c.GetHeader("If-None-Match"), etag) {
|
||||
c.Status(http.StatusNotModified)
|
||||
c.Writer.WriteHeaderNow()
|
||||
return
|
||||
}
|
||||
if c.Request.Method == http.MethodHead {
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
c.Header("Content-Length", strconv.Itoa(len(page)))
|
||||
c.Status(http.StatusOK)
|
||||
c.Writer.WriteHeaderNow()
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "text/html; charset=utf-8", page)
|
||||
}
|
||||
|
||||
// IsDocumentPath guards the NoRoute handler. Caddy already filters document
|
||||
// requests, but this keeps direct backend requests from turning API/static
|
||||
// misses into HTML responses.
|
||||
func IsDocumentPath(path string) bool {
|
||||
if path == "" || path == "/" {
|
||||
return true
|
||||
}
|
||||
for _, prefix := range []string{"/api", "/r", "/health", "/assets", "/swagger", "/docs"} {
|
||||
if path == prefix || strings.HasPrefix(path, prefix+"/") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
segment := path
|
||||
if index := strings.LastIndex(path, "/"); index >= 0 {
|
||||
segment = path[index+1:]
|
||||
}
|
||||
return !strings.Contains(segment, ".")
|
||||
}
|
||||
|
||||
func MetaFromRequest(c *gin.Context) Meta {
|
||||
profile := map[string]any{}
|
||||
tenantCode := ""
|
||||
tenantName := ""
|
||||
if scope, ok := tenancy.FromContext(c.Request.Context()); ok {
|
||||
profile = scope.Profile()
|
||||
tenantCode = scope.TenantCode
|
||||
tenantName = scope.TenantName
|
||||
}
|
||||
|
||||
scheme := strings.TrimSpace(c.GetHeader("X-Forwarded-Proto"))
|
||||
if scheme == "" {
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
} else {
|
||||
scheme = "http"
|
||||
}
|
||||
}
|
||||
host := sitecode.ExtractHost(c.Request.Host)
|
||||
if host == "" {
|
||||
host = c.Request.Host
|
||||
}
|
||||
path := c.Request.URL.EscapedPath()
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
return BuildMeta(profile, tenantCode, tenantName, scheme, host, path)
|
||||
}
|
||||
|
||||
func etagMatches(header, etag string) bool {
|
||||
for _, part := range strings.Split(header, ",") {
|
||||
if strings.TrimSpace(part) == etag {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const unavailablePage = `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>页面暂时不可用</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:48px 24px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;text-align:center;color:#1f2937">
|
||||
<h1 style="font-size:22px;margin:0 0 12px">页面暂时不可用</h1>
|
||||
<p style="margin:0;color:#6b7280">请稍后刷新重试。</p>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
func writeUnavailable(c *gin.Context) {
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.Header("Retry-After", "3")
|
||||
c.Data(http.StatusServiceUnavailable, "text/html; charset=utf-8", []byte(unavailablePage))
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package storefrontshell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/datatypes"
|
||||
)
|
||||
|
||||
type fakeTenantResolver struct{}
|
||||
|
||||
func (fakeTenantResolver) ResolveHost(_ context.Context, host string) (*tenancy.Scope, error) {
|
||||
if strings.Contains(host, "zuhaox.com") {
|
||||
return &tenancy.Scope{
|
||||
TenantID: 2,
|
||||
TenantCode: "jieyou",
|
||||
TenantName: "解忧商行",
|
||||
TenantStatus: "active",
|
||||
Host: host,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (fakeTenantResolver) ResolveCode(context.Context, string) (*tenancy.Scope, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type staticProvider struct {
|
||||
body []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (p staticProvider) Get(context.Context) ([]byte, error) {
|
||||
return p.body, p.err
|
||||
}
|
||||
|
||||
func TestBuildMetaJieyouFallbacks(t *testing.T) {
|
||||
meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/")
|
||||
|
||||
if meta.Title != "解忧商行 - 官方租号平台" {
|
||||
t.Fatalf("Title = %q", meta.Title)
|
||||
}
|
||||
if meta.FaviconURL != "/jieyou-favicon.svg" {
|
||||
t.Fatalf("FaviconURL = %q", meta.FaviconURL)
|
||||
}
|
||||
if meta.AppleIconURL != "/jieyou-apple-touch-icon.png" {
|
||||
t.Fatalf("AppleIconURL = %q", meta.AppleIconURL)
|
||||
}
|
||||
if meta.ThemeColor != "#a64332" {
|
||||
t.Fatalf("ThemeColor = %q", meta.ThemeColor)
|
||||
}
|
||||
if meta.Canonical != "https://zuhaox.com/" {
|
||||
t.Fatalf("Canonical = %q", meta.Canonical)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMetaRejectsUnsafeAssetURL(t *testing.T) {
|
||||
meta := BuildMeta(map[string]any{
|
||||
"site_name": "测试站",
|
||||
"favicon_url": "javascript:alert(1)",
|
||||
"logo_url": "data:text/html,<script>alert(1)</script>",
|
||||
}, "custom", "", "https", "example.com", "/")
|
||||
|
||||
if meta.FaviconURL != "" {
|
||||
t.Fatalf("FaviconURL = %q, want empty", meta.FaviconURL)
|
||||
}
|
||||
if meta.OGImageURL != "" {
|
||||
t.Fatalf("OGImageURL = %q, want empty", meta.OGImageURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMetaEscapesProfileValues(t *testing.T) {
|
||||
meta := BuildMeta(
|
||||
map[string]any{"site_name": `<script>alert("x")</script>`},
|
||||
"custom", "", "https", "example.com", "/",
|
||||
)
|
||||
block := meta.HTML(true)
|
||||
|
||||
if strings.Contains(block, "<script>") {
|
||||
t.Fatalf("HTML block contains an unescaped script tag: %s", block)
|
||||
}
|
||||
if !strings.Contains(block, "<script>") {
|
||||
t.Fatalf("HTML block did not escape the site name: %s", block)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectReplacesPlaceholder(t *testing.T) {
|
||||
shell := []byte(`<html><head><meta name="site-shell-placeholder" content="1" /><title>官方租号平台</title><link id="site-apple-touch-icon" rel="apple-touch-icon" href="/apple-touch-icon.png" /><link id="site-icon" rel="icon" type="image/png" href="/apple-touch-icon.png" /></head><body><div id="app"></div></body></html>`)
|
||||
meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/")
|
||||
out := string(Inject(shell, meta))
|
||||
|
||||
if strings.Contains(out, "site-shell-placeholder") {
|
||||
t.Fatalf("placeholder was not replaced: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "<title>解忧商行 - 官方租号平台</title>") {
|
||||
t.Fatalf("title was not injected: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `name="site-shell" content="server"`) {
|
||||
t.Fatalf("site-shell marker missing: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `href="/jieyou-favicon.svg"`) {
|
||||
t.Fatalf("favicon was not injected: %s", out)
|
||||
}
|
||||
if strings.Count(out, `id="site-icon"`) != 1 {
|
||||
t.Fatalf("expected exactly one site-icon link, got: %s", out)
|
||||
}
|
||||
if strings.Count(out, `id="site-apple-touch-icon"`) != 1 {
|
||||
t.Fatalf("expected exactly one site-apple-touch-icon link, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectFallsBackToTitleReplacement(t *testing.T) {
|
||||
shell := []byte(`<html><head><title>官方租号平台</title><script src="/site-bootstrap.js"></script></head><body></body></html>`)
|
||||
meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/")
|
||||
out := string(Inject(shell, meta))
|
||||
|
||||
if strings.Count(out, "<title>") != 1 {
|
||||
t.Fatalf("expected exactly one title tag, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "<title>解忧商行 - 官方租号平台</title>") {
|
||||
t.Fatalf("title was not replaced: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `name="description"`) {
|
||||
t.Fatalf("description was not injected: %s", out)
|
||||
}
|
||||
shellMarker := strings.Index(out, `name="site-shell"`)
|
||||
script := strings.Index(out, "site-bootstrap.js")
|
||||
if shellMarker < 0 || script < 0 || shellMarker > script {
|
||||
t.Fatalf("site-shell marker must appear before site-bootstrap.js: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderRevalidatesWithETag(t *testing.T) {
|
||||
requests := 0
|
||||
conditional := ""
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
if r.Header.Get("If-None-Match") == `"v1"` {
|
||||
conditional = r.Header.Get("If-None-Match")
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"v1"`)
|
||||
_, _ = w.Write([]byte(`<html><head></head><body>shell</body></html>`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
provider := NewProvider(server.URL, zap.NewNop())
|
||||
provider.ttl = 0
|
||||
|
||||
first, err := provider.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("first Get: %v", err)
|
||||
}
|
||||
second, err := provider.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("second Get: %v", err)
|
||||
}
|
||||
if string(first) != string(second) {
|
||||
t.Fatalf("cached body changed: %q vs %q", first, second)
|
||||
}
|
||||
if requests != 2 {
|
||||
t.Fatalf("requests = %d, want 2", requests)
|
||||
}
|
||||
if conditional != `"v1"` {
|
||||
t.Fatalf("conditional header = %q", conditional)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerServesTenantShell(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(staticProvider{body: []byte(
|
||||
`<html><head><meta name="site-shell-placeholder" content="1" /><title>官方租号平台</title></head><body><div id="app"></div></body></html>`,
|
||||
)}, zap.NewNop())
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
req := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/listings/1", nil)
|
||||
req.Header.Set("X-Forwarded-Proto", "https")
|
||||
req = req.WithContext(tenancy.WithScope(req.Context(), tenancy.Scope{
|
||||
TenantID: 2,
|
||||
TenantCode: "jieyou",
|
||||
TenantName: "解忧商行",
|
||||
ProfileJSON: datatypes.JSON([]byte(`{"site_name":"解忧商行"}`)),
|
||||
}))
|
||||
c.Request = req
|
||||
|
||||
handler.Serve(c)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", recorder.Code)
|
||||
}
|
||||
body := recorder.Body.String()
|
||||
if !strings.Contains(body, "<title>解忧商行 - 官方租号平台</title>") {
|
||||
t.Fatalf("body missing tenant title: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `href="/jieyou-apple-touch-icon.png"`) {
|
||||
t.Fatalf("body missing tenant apple icon: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `rel="canonical" href="https://zuhaox.com/listings/1"`) {
|
||||
t.Fatalf("body missing canonical: %s", body)
|
||||
}
|
||||
if got := recorder.Header().Get("Vary"); got != "Host" {
|
||||
t.Fatalf("Vary = %q, want Host", got)
|
||||
}
|
||||
if got := recorder.Header().Get("Cache-Control"); got != "no-cache" {
|
||||
t.Fatalf("Cache-Control = %q, want no-cache", got)
|
||||
}
|
||||
if got := recorder.Header().Get("ETag"); got == "" {
|
||||
t.Fatal("ETag is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerSupportsConditionalRequest(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(staticProvider{body: []byte(
|
||||
`<html><head><meta name="site-shell-placeholder" content="1" /><title>官方租号平台</title></head><body></body></html>`,
|
||||
)}, zap.NewNop())
|
||||
|
||||
first := httptest.NewRecorder()
|
||||
firstContext, _ := gin.CreateTestContext(first)
|
||||
firstRequest := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil)
|
||||
firstRequest = firstRequest.WithContext(tenancy.WithScope(firstRequest.Context(), tenancy.Scope{
|
||||
TenantID: 2,
|
||||
TenantCode: "jieyou",
|
||||
TenantName: "解忧商行",
|
||||
}))
|
||||
firstContext.Request = firstRequest
|
||||
handler.Serve(firstContext)
|
||||
|
||||
etag := first.Header().Get("ETag")
|
||||
if etag == "" {
|
||||
t.Fatal("first response has no ETag")
|
||||
}
|
||||
|
||||
second := httptest.NewRecorder()
|
||||
secondContext, _ := gin.CreateTestContext(second)
|
||||
secondRequest := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil)
|
||||
secondRequest.Header.Set("If-None-Match", etag)
|
||||
secondRequest = secondRequest.WithContext(tenancy.WithScope(secondRequest.Context(), tenancy.Scope{
|
||||
TenantID: 2,
|
||||
TenantCode: "jieyou",
|
||||
TenantName: "解忧商行",
|
||||
}))
|
||||
secondContext.Request = secondRequest
|
||||
handler.Serve(secondContext)
|
||||
|
||||
if second.Code != http.StatusNotModified {
|
||||
t.Fatalf("status = %d, want 304 (etag=%q responseETag=%q ifNoneMatch=%q)", second.Code, etag, second.Header().Get("ETag"), secondRequest.Header.Get("If-None-Match"))
|
||||
}
|
||||
if second.Body.Len() != 0 {
|
||||
t.Fatalf("304 body = %q, want empty", second.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerRejectsAPIPath(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(staticProvider{body: []byte("<html></html>")}, zap.NewNop())
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "http://zuhaox.com/api/unknown", nil)
|
||||
|
||||
handler.Serve(c)
|
||||
|
||||
if recorder.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", recorder.Code)
|
||||
}
|
||||
if !strings.Contains(recorder.Header().Get("Content-Type"), "application/json") {
|
||||
t.Fatalf("content type = %q, want JSON", recorder.Header().Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerReturnsUnavailableWhenShellFails(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
handler := NewHandler(staticProvider{err: context.DeadlineExceeded}, zap.NewNop())
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil)
|
||||
|
||||
handler.Serve(c)
|
||||
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", recorder.Code)
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "页面暂时不可用") {
|
||||
t.Fatalf("body = %q", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoRouteUsesTenantContext(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(middleware.TenantContext(fakeTenantResolver{}, "production", zap.NewNop(), "dachui"))
|
||||
handler := NewHandler(staticProvider{body: []byte(
|
||||
`<html><head><title>官方租号平台</title><meta name="site-shell-placeholder" content="1" /></head><body></body></html>`,
|
||||
)}, zap.NewNop())
|
||||
engine.NoRoute(handler.Serve)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil)
|
||||
request.Header.Set("X-Forwarded-Proto", "https")
|
||||
engine.ServeHTTP(recorder, request)
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", recorder.Code)
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), "<title>解忧商行 - 官方租号平台</title>") {
|
||||
t.Fatalf("body missing tenant title: %s", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
// Package storefrontshell turns the built SPA index.html into a per-host HTML
|
||||
// shell. Tenant names, icons and SEO tags are resolved on the server so that
|
||||
// crawlers and link previews do not see the main-site brand on tenant domains.
|
||||
package storefrontshell
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
maxShellBytes = 2 << 20
|
||||
shellCacheTTL = 3 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
shellPlaceholderPattern = regexp.MustCompile(`(?is)<meta\s+name=["']site-shell-placeholder["'][^>]*>`)
|
||||
fallbackIconLinkPattern = regexp.MustCompile(`(?is)<link\s+[^>]*id=["']site-(?:apple-touch-)?icon["'][^>]*>\s*`)
|
||||
titlePattern = regexp.MustCompile(`(?is)<title>.*?</title>`)
|
||||
headPattern = regexp.MustCompile(`(?is)<head[^>]*>`)
|
||||
)
|
||||
|
||||
// Provider fetches and caches the built index.html from Caddy's internal
|
||||
// storefront-shell endpoint. The endpoint serves the exact artifact that Caddy
|
||||
// is serving, so asset hashes always stay in sync with the frontend build.
|
||||
type Provider struct {
|
||||
url string
|
||||
client *http.Client
|
||||
logger *zap.Logger
|
||||
ttl time.Duration
|
||||
|
||||
mu sync.RWMutex
|
||||
body []byte
|
||||
etag string
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
func NewProvider(url string, logger *zap.Logger) *Provider {
|
||||
return &Provider{
|
||||
url: strings.TrimSpace(url),
|
||||
client: &http.Client{Timeout: 3 * time.Second},
|
||||
logger: logger,
|
||||
ttl: shellCacheTTL,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Provider) Get(ctx context.Context) ([]byte, error) {
|
||||
if p == nil || p.url == "" {
|
||||
return nil, fmt.Errorf("storefront shell url is empty")
|
||||
}
|
||||
|
||||
p.mu.RLock()
|
||||
body := append([]byte(nil), p.body...)
|
||||
etag := p.etag
|
||||
fetchedAt := p.fetchedAt
|
||||
p.mu.RUnlock()
|
||||
|
||||
if len(body) > 0 && time.Since(fetchedAt) < p.ttl {
|
||||
return body, nil
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if etag != "" {
|
||||
req.Header.Set("If-None-Match", etag)
|
||||
}
|
||||
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
if len(body) > 0 {
|
||||
p.warn("读取前台 HTML 模板失败,使用上次缓存", err)
|
||||
return body, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotModified:
|
||||
if len(body) == 0 {
|
||||
return nil, fmt.Errorf("storefront shell returned 304 without cache")
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.fetchedAt = time.Now()
|
||||
p.mu.Unlock()
|
||||
return body, nil
|
||||
case http.StatusOK:
|
||||
data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxShellBytes))
|
||||
if readErr != nil {
|
||||
if len(body) > 0 {
|
||||
p.warn("读取前台 HTML 模板失败,使用上次缓存", readErr)
|
||||
return body, nil
|
||||
}
|
||||
return nil, readErr
|
||||
}
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
return nil, fmt.Errorf("storefront shell is empty")
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.body = data
|
||||
p.etag = resp.Header.Get("ETag")
|
||||
p.fetchedAt = time.Now()
|
||||
p.mu.Unlock()
|
||||
return data, nil
|
||||
default:
|
||||
if len(body) > 0 {
|
||||
p.warn(fmt.Sprintf("读取前台 HTML 模板返回 %d,使用上次缓存", resp.StatusCode), nil)
|
||||
return body, nil
|
||||
}
|
||||
return nil, fmt.Errorf("storefront shell status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Provider) warn(message string, err error) {
|
||||
if p.logger == nil {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
p.logger.Warn(message, zap.Error(err))
|
||||
return
|
||||
}
|
||||
p.logger.Warn(message)
|
||||
}
|
||||
|
||||
// Meta holds the tenant-specific values injected into the HTML shell.
|
||||
type Meta struct {
|
||||
SiteCode string
|
||||
SiteName string
|
||||
Title string
|
||||
Description string
|
||||
Canonical string
|
||||
FaviconURL string
|
||||
AppleIconURL string
|
||||
ThemeColor string
|
||||
OGImageURL string
|
||||
}
|
||||
|
||||
// BuildMeta derives SEO and brand metadata from the tenant profile. Missing
|
||||
// profile fields fall back to the same defaults used by the SPA.
|
||||
func BuildMeta(profile map[string]any, tenantCode, tenantName, scheme, host, path string) Meta {
|
||||
if profile == nil {
|
||||
profile = map[string]any{}
|
||||
}
|
||||
|
||||
siteName := firstNonEmpty(stringValue(profile, "site_name"), tenantName, "官方租号平台")
|
||||
title := "官方租号平台"
|
||||
if siteName != "" && !strings.Contains(siteName, "官方租号平台") {
|
||||
title = siteName + " - 官方租号平台"
|
||||
} else if siteName != "" {
|
||||
title = siteName
|
||||
}
|
||||
|
||||
description := firstNonEmpty(stringValue(profile, "seo_description"), storefrontDescription(profile))
|
||||
if description == "" {
|
||||
if siteName != "" && siteName != "官方租号平台" {
|
||||
description = siteName + "官方租号平台,精选三角洲行动账号,逐号核验、独立订单与专属售后。"
|
||||
} else {
|
||||
description = "精选三角洲行动账号租赁平台,逐号核验、独立订单与专属售后。"
|
||||
}
|
||||
}
|
||||
|
||||
favicon, appleIcon, themeColor := fallbackBrand(tenantCode)
|
||||
favicon = safeAssetURL(firstNonEmpty(stringValue(profile, "favicon_url"), favicon))
|
||||
appleIcon = safeAssetURL(firstNonEmpty(stringValue(profile, "apple_touch_icon_url"), appleIcon))
|
||||
themeColor = firstNonEmpty(stringValue(profile, "theme_color"), themeColor)
|
||||
|
||||
ogImage := safeAssetURL(firstNonEmpty(stringValue(profile, "og_image_url"), stringValue(profile, "logo_url")))
|
||||
ogImage = absoluteURL(scheme, host, ogImage)
|
||||
|
||||
canonicalPath := path
|
||||
if canonicalPath == "" {
|
||||
canonicalPath = "/"
|
||||
}
|
||||
if !strings.HasPrefix(canonicalPath, "/") {
|
||||
canonicalPath = "/" + canonicalPath
|
||||
}
|
||||
canonical := ""
|
||||
if scheme != "" && host != "" {
|
||||
canonical = scheme + "://" + host + canonicalPath
|
||||
}
|
||||
|
||||
return Meta{
|
||||
SiteCode: strings.TrimSpace(tenantCode),
|
||||
SiteName: siteName,
|
||||
Title: title,
|
||||
Description: description,
|
||||
Canonical: canonical,
|
||||
FaviconURL: favicon,
|
||||
AppleIconURL: appleIcon,
|
||||
ThemeColor: themeColor,
|
||||
OGImageURL: ogImage,
|
||||
}
|
||||
}
|
||||
|
||||
func (m Meta) HTML(includeTitle bool) string {
|
||||
var b strings.Builder
|
||||
if includeTitle {
|
||||
fmt.Fprintf(&b, "<title>%s</title>\n", html.EscapeString(m.Title))
|
||||
}
|
||||
fmt.Fprintf(&b, `<meta name="site-shell" content="server" />`+"\n")
|
||||
fmt.Fprintf(&b, `<meta name="site-code" content="%s" />`+"\n", html.EscapeString(m.SiteCode))
|
||||
fmt.Fprintf(&b, `<meta name="site-name" content="%s" />`+"\n", html.EscapeString(m.SiteName))
|
||||
fmt.Fprintf(&b, `<meta name="description" content="%s" />`+"\n", html.EscapeString(m.Description))
|
||||
fmt.Fprintf(&b, `<meta name="theme-color" content="%s" />`+"\n", html.EscapeString(m.ThemeColor))
|
||||
fmt.Fprintf(&b, `<meta property="og:type" content="website" />`+"\n")
|
||||
fmt.Fprintf(&b, `<meta property="og:site_name" content="%s" />`+"\n", html.EscapeString(m.SiteName))
|
||||
fmt.Fprintf(&b, `<meta property="og:title" content="%s" />`+"\n", html.EscapeString(m.Title))
|
||||
fmt.Fprintf(&b, `<meta property="og:description" content="%s" />`+"\n", html.EscapeString(m.Description))
|
||||
if m.Canonical != "" {
|
||||
fmt.Fprintf(&b, `<meta property="og:url" content="%s" />`+"\n", html.EscapeString(m.Canonical))
|
||||
fmt.Fprintf(&b, `<link rel="canonical" href="%s" />`+"\n", html.EscapeString(m.Canonical))
|
||||
}
|
||||
if m.OGImageURL != "" {
|
||||
fmt.Fprintf(&b, `<meta property="og:image" content="%s" />`+"\n", html.EscapeString(m.OGImageURL))
|
||||
}
|
||||
fmt.Fprintf(&b, `<meta name="twitter:card" content="summary" />`+"\n")
|
||||
if m.FaviconURL != "" {
|
||||
fmt.Fprintf(&b, `<link id="site-icon" rel="icon" type="%s" href="%s" />`+"\n", iconType(m.FaviconURL), html.EscapeString(m.FaviconURL))
|
||||
}
|
||||
if m.AppleIconURL != "" {
|
||||
fmt.Fprintf(&b, `<link id="site-apple-touch-icon" rel="apple-touch-icon" href="%s" />`+"\n", html.EscapeString(m.AppleIconURL))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Inject replaces the placeholder block in the built index.html. The title is
|
||||
// always replaced separately so the fallback title does not become a duplicate
|
||||
// tag when the server injects description, OG and icon metadata.
|
||||
func Inject(shell []byte, meta Meta) []byte {
|
||||
if len(shell) == 0 {
|
||||
return shell
|
||||
}
|
||||
|
||||
out := fallbackIconLinkPattern.ReplaceAll(shell, nil)
|
||||
if titlePattern.Match(out) {
|
||||
out = titlePattern.ReplaceAll(out, []byte("<title>"+html.EscapeString(meta.Title)+"</title>"))
|
||||
}
|
||||
if loc := shellPlaceholderPattern.FindIndex(out); loc != nil {
|
||||
block := []byte(meta.HTML(false))
|
||||
merged := make([]byte, 0, len(out)+len(block))
|
||||
merged = append(merged, out[:loc[0]]...)
|
||||
merged = append(merged, block...)
|
||||
merged = append(merged, out[loc[1]:]...)
|
||||
return merged
|
||||
}
|
||||
if idx := bytes.Index(out, []byte("</head>")); idx >= 0 {
|
||||
extra := []byte(meta.HTML(false))
|
||||
// 旧版 HTML 没有占位块时,把注入内容放在 <head> 开头,
|
||||
// 确保 site-bootstrap.js 执行前已经能看到 site-shell 标记。
|
||||
if head := headPattern.FindIndex(out); head != nil {
|
||||
merged := make([]byte, 0, len(out)+len(extra))
|
||||
merged = append(merged, out[:head[1]]...)
|
||||
merged = append(merged, extra...)
|
||||
merged = append(merged, out[head[1]:]...)
|
||||
return merged
|
||||
}
|
||||
merged := make([]byte, 0, len(out)+len(extra))
|
||||
merged = append(merged, out[:idx]...)
|
||||
merged = append(merged, extra...)
|
||||
merged = append(merged, out[idx:]...)
|
||||
return merged
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ETag returns a stable validator for the rendered shell. It includes both the
|
||||
// source shell and the tenant metadata so title/profile changes invalidate it.
|
||||
func ETag(meta Meta, shell []byte) string {
|
||||
sum := sha256.New()
|
||||
_, _ = sum.Write(shell)
|
||||
_, _ = sum.Write([]byte(meta.HTML(true)))
|
||||
return `"` + hex.EncodeToString(sum.Sum(nil)[:16]) + `"`
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func stringValue(values map[string]any, key string) string {
|
||||
if values == nil {
|
||||
return ""
|
||||
}
|
||||
value, ok := values[key]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
text, _ := value.(string)
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
func storefrontDescription(profile map[string]any) string {
|
||||
if profile == nil {
|
||||
return ""
|
||||
}
|
||||
raw, ok := profile["storefront_text_json"]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
switch value := raw.(type) {
|
||||
case string:
|
||||
var payload struct {
|
||||
HeroDesc string `json:"hero_desc"`
|
||||
}
|
||||
if json.Unmarshal([]byte(value), &payload) == nil {
|
||||
return strings.TrimSpace(payload.HeroDesc)
|
||||
}
|
||||
case map[string]any:
|
||||
return stringValue(value, "hero_desc")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func fallbackBrand(tenantCode string) (favicon, appleIcon, themeColor string) {
|
||||
switch strings.ToLower(strings.TrimSpace(tenantCode)) {
|
||||
case "jieyou":
|
||||
return "/jieyou-favicon.svg", "/jieyou-apple-touch-icon.png", "#a64332"
|
||||
case "dachui":
|
||||
return "/apple-touch-icon.png", "/apple-touch-icon.png", "#ff6a00"
|
||||
default:
|
||||
return "/apple-touch-icon.png", "/apple-touch-icon.png", "#ff6a00"
|
||||
}
|
||||
}
|
||||
|
||||
func iconType(url string) string {
|
||||
path := strings.SplitN(url, "?", 2)[0]
|
||||
if strings.HasSuffix(strings.ToLower(path), ".svg") {
|
||||
return "image/svg+xml"
|
||||
}
|
||||
return "image/png"
|
||||
}
|
||||
|
||||
// safeAssetURL 只允许站内相对路径、http(s)、协议相对地址和 data:image。
|
||||
// 租户品牌字段来自后台,仍按不可信输入处理,避免 javascript: 等 URL 进入 head。
|
||||
func safeAssetURL(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
lower := strings.ToLower(value)
|
||||
if strings.HasPrefix(value, "/") ||
|
||||
strings.HasPrefix(lower, "http://") ||
|
||||
strings.HasPrefix(lower, "https://") ||
|
||||
strings.HasPrefix(value, "//") ||
|
||||
strings.HasPrefix(lower, "data:image/") {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func absoluteURL(scheme, host, value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") || strings.HasPrefix(value, "//") {
|
||||
return value
|
||||
}
|
||||
if strings.HasPrefix(value, "/") && scheme != "" && host != "" {
|
||||
return scheme + "://" + host + value
|
||||
}
|
||||
return value
|
||||
}
|
||||
Reference in New Issue
Block a user