SitemapController.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Text;
  2. using Microsoft.AspNetCore.Mvc;
  3. using CoupangRequest = goods.Models.Coupang.Request;
  4. namespace goods.Controllers
  5. {
  6. // sitemap.xml 생성
  7. // 카테고리/PL 목록은 Request.Categories, Request.Brand enum 에서 그대로 읽는다.
  8. // HomeController 가 Enum.IsDefined 로 유효성을 검사하므로, enum 에 없는 ID 는 애초에 400 이 되고
  9. // enum 에 추가된 ID 는 별도 작업 없이 sitemap 에 함께 노출된다.
  10. public class SitemapController : Controller
  11. {
  12. // 사이트 정식 주소. 리버스 프록시 뒤에서는 Request.Scheme 이 http 로 들어올 수 있어
  13. // 설정값(Site:BaseUrl)을 우선 사용하고, 없으면 운영 도메인을 쓴다.
  14. private const string DefaultBaseUrl = "https://goods.web.or.kr";
  15. private readonly IConfiguration _configuration;
  16. public SitemapController(IConfiguration configuration)
  17. {
  18. _configuration = configuration;
  19. }
  20. // HEAD 도 함께 받는다. 정적 파일일 때는 StaticFiles 미들웨어가 HEAD 를 처리해 줬지만
  21. // 어트리뷰트 라우팅은 HttpGet 만 두면 HEAD 요청에 405 를 반환한다.
  22. [HttpGet("/sitemap.xml")]
  23. [HttpHead("/sitemap.xml")]
  24. [ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Any)]
  25. public IActionResult Index()
  26. {
  27. var baseUrl = (_configuration["Site:BaseUrl"] ?? DefaultBaseUrl).TrimEnd('/');
  28. // 목록 페이지는 쿠팡 API 응답에 따라 매일 내용이 바뀌므로 날짜 단위로만 표기한다.
  29. var today = DateTime.UtcNow.ToString("yyyy-MM-dd");
  30. var builder = new StringBuilder();
  31. builder.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
  32. builder.AppendLine(@"<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">");
  33. // 홈
  34. AppendUrl(builder, $"{baseUrl}/", today, "daily", "1.0");
  35. // 골드박스, 이벤트
  36. AppendUrl(builder, $"{baseUrl}/GoldBox", today, "daily", "0.8");
  37. AppendUrl(builder, $"{baseUrl}/Event", today, "weekly", "0.8");
  38. // 카테고리별 베스트 상품
  39. foreach (var id in Enum.GetValues<CoupangRequest.Categories>().Select(value => (int)value).Distinct().OrderBy(id => id))
  40. {
  41. AppendUrl(builder, $"{baseUrl}/category/{id}", today, "daily", "0.8");
  42. }
  43. // 쿠팡PL 브랜드별 상품
  44. foreach (var id in Enum.GetValues<CoupangRequest.Brand>().Select(value => (int)value).Distinct().OrderBy(id => id))
  45. {
  46. AppendUrl(builder, $"{baseUrl}/pl/{id}", today, "daily", "0.8");
  47. }
  48. builder.AppendLine("</urlset>");
  49. // 검색(/search)은 keyword 없이는 400 을 반환하는 파라미터 페이지라 제외한다.
  50. return Content(builder.ToString(), "application/xml", Encoding.UTF8);
  51. }
  52. private static void AppendUrl(StringBuilder builder, string location, string lastModified, string changeFrequency, string priority)
  53. {
  54. builder.AppendLine(" <url>");
  55. builder.AppendLine($" <loc>{location}</loc>");
  56. builder.AppendLine($" <lastmod>{lastModified}</lastmod>");
  57. builder.AppendLine($" <changefreq>{changeFrequency}</changefreq>");
  58. builder.AppendLine($" <priority>{priority}</priority>");
  59. builder.AppendLine(" </url>");
  60. }
  61. }
  62. }