From ad2b9b9c6446f5dade6c6f1b2cc4cd224c7d5d71 Mon Sep 17 00:00:00 2001 From: Ryan Wang Date: Mon, 27 Apr 2026 16:55:03 +0800 Subject: [PATCH] chore: minor code quality improvements - Replace String.replaceAll() with String.replace() in UrlUtils.escapeSitemapUrl() for literal string substitutions; replaceAll() compiles a regex pattern on every call which is unnecessary overhead for plain string replacement - Set Content-Type to text/xml;charset=UTF-8 in the sitemap endpoint to make the charset explicit instead of relying on client-side inference - Return HTTP 204 No Content when the sitemap is empty rather than serving an empty body with 200 OK Made-with: Cursor --- .../java/run/halo/sitemap/SitemapPluginConfig.java | 6 +++++- src/main/java/run/halo/sitemap/UrlUtils.java | 10 +++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/run/halo/sitemap/SitemapPluginConfig.java b/src/main/java/run/halo/sitemap/SitemapPluginConfig.java index 1989351..7f366c8 100644 --- a/src/main/java/run/halo/sitemap/SitemapPluginConfig.java +++ b/src/main/java/run/halo/sitemap/SitemapPluginConfig.java @@ -3,6 +3,7 @@ import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.accept; +import java.nio.charset.StandardCharsets; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.context.annotation.Bean; @@ -33,9 +34,12 @@ RouterFunction sitemapRouterFunction(CachedSitemapGetter cachedS var options = SitemapGeneratorOptions.builder() .siteUrl(url) .build(); + var xmlMediaType = new MediaType(MediaType.TEXT_XML, StandardCharsets.UTF_8); return cachedSitemapGetter.get(options) + .filter(sitemap -> !sitemap.isBlank()) .flatMap(sitemap -> ServerResponse.ok() - .contentType(MediaType.TEXT_XML).bodyValue(sitemap)); + .contentType(xmlMediaType).bodyValue(sitemap)) + .switchIfEmpty(ServerResponse.noContent().build()); } ); } diff --git a/src/main/java/run/halo/sitemap/UrlUtils.java b/src/main/java/run/halo/sitemap/UrlUtils.java index c633eb8..5dc4a25 100644 --- a/src/main/java/run/halo/sitemap/UrlUtils.java +++ b/src/main/java/run/halo/sitemap/UrlUtils.java @@ -20,11 +20,11 @@ public final class UrlUtils { */ public static String escapeSitemapUrl(String url) { Assert.notNull(url, "The url must not be null"); - return url.replaceAll("&", "&") - .replaceAll("'", "'") - .replaceAll("\"", """) - .replaceAll(">", ">") - .replaceAll("<", "<"); + return url.replace("&", "&") + .replace("'", "'") + .replace("\"", """) + .replace(">", ">") + .replace("<", "<"); } public static URI toURI(String s) {