diff --git a/internal/handler/autoindex.go b/internal/handler/autoindex.go index dec81b4..da2e68a 100644 --- a/internal/handler/autoindex.go +++ b/internal/handler/autoindex.go @@ -11,6 +11,8 @@ import ( "encoding/json" "encoding/xml" "fmt" + "html" + "net/url" "os" "sort" "strings" @@ -115,7 +117,7 @@ func generateHTMLIndex(ctx *fasthttp.RequestCtx, reqPath string, entries []dirEn // HTML 头部 buf.WriteString("\n") buf.WriteString("\n\n") - buf.WriteString(fmt.Sprintf("Index of %s\n", escapeHTML(reqPath))) + buf.WriteString(fmt.Sprintf("Index of %s\n", html.EscapeString(reqPath))) buf.WriteString("\n") buf.WriteString("\n\n") - buf.WriteString(fmt.Sprintf("

Index of %s

\n", escapeHTML(reqPath))) + buf.WriteString(fmt.Sprintf("

Index of %s

\n", html.EscapeString(reqPath))) buf.WriteString("
\n\n") buf.WriteString("\n") buf.WriteString("\n") @@ -140,7 +142,7 @@ func generateHTMLIndex(ctx *fasthttp.RequestCtx, reqPath string, entries []dirEn for _, entry := range entries { name := entry.Name displayName := name - href := escapeURL(name) + href := url.PathEscape(name) if entry.IsDir { displayName += "/" @@ -166,11 +168,12 @@ func generateHTMLIndex(ctx *fasthttp.RequestCtx, reqPath string, entries []dirEn } buf.WriteString(fmt.Sprintf("\n", - href, escapeHTML(displayName), timeStr, sizeStr)) + href, html.EscapeString(displayName), timeStr, sizeStr)) } buf.WriteString("\n
NameModifiedSize
%s%s%s
\n
\n\n\n") + ctx.Response.Header.Set("Content-Security-Policy", "default-src 'self'") ctx.Response.Header.SetContentType("text/html; charset=utf-8") ctx.Response.SetBody(buf.Bytes()) } @@ -275,27 +278,3 @@ func formatSize(size int64) string { } } -// escapeHTML 转义 HTML 特殊字符。 -func escapeHTML(s string) string { - s = strings.ReplaceAll(s, "&", "&") - s = strings.ReplaceAll(s, "<", "<") - s = strings.ReplaceAll(s, ">", ">") - s = strings.ReplaceAll(s, "\"", """) - s = strings.ReplaceAll(s, "'", "'") - return s -} - -// escapeURL 转义 URL 特殊字符。 -func escapeURL(s string) string { - var buf bytes.Buffer - for _, c := range s { - // 保留安全字符 - if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || - c == '-' || c == '_' || c == '.' || c == '~' || c == '/' { - buf.WriteRune(c) - } else { - buf.WriteString(fmt.Sprintf("%%%02X", c)) - } - } - return buf.String() -} diff --git a/internal/handler/autoindex_test.go b/internal/handler/autoindex_test.go index 9c47eae..4104065 100644 --- a/internal/handler/autoindex_test.go +++ b/internal/handler/autoindex_test.go @@ -2,6 +2,7 @@ package handler import ( + "fmt" "os" "path/filepath" "testing" @@ -233,42 +234,25 @@ func TestFormatSize(t *testing.T) { } } -func TestEscapeHTML(t *testing.T) { - tests := []struct { - input string - expected string - }{ - {"normal", "normal"}, - {"