From 2f1c5d0d837af7ca3c2ae9efd1b70a3529b37883 Mon Sep 17 00:00:00 2001 From: Giovanni Harting <539@idlegandalf.com> Date: Sat, 4 Mar 2023 14:41:25 +0100 Subject: [PATCH] added gzip compression to sitemap endpoints --- main.go | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 4132faf..3c70b17 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "compress/gzip" "context" "encoding/gob" "entgo.io/ent/dialect" @@ -1059,12 +1060,24 @@ func getSiteMapIndex(c *gin.Context) { return } + var compBytes bytes.Buffer + compWriter := gzip.NewWriter(&compBytes) + if _, err = compWriter.Write(res); err != nil { + _ = c.AbortWithError(http.StatusInternalServerError, err) + return + } + if err = compWriter.Close(); err != nil { + _ = c.AbortWithError(http.StatusInternalServerError, err) + return + } + + c.Header("Content-Encoding", "gzip") if c.Request.Method == http.MethodHead { - c.Header("Content-Length", strconv.Itoa(len(res))) + c.Header("Content-Length", strconv.Itoa(compBytes.Len())) c.Header("Content-Type", "application/xml") c.Status(http.StatusOK) } else { - c.Data(http.StatusOK, "application/xml", res) + c.Data(http.StatusOK, "application/xml", compBytes.Bytes()) } } @@ -1091,12 +1104,24 @@ func getSiteMap(c *gin.Context) { return } + var compBytes bytes.Buffer + compWriter := gzip.NewWriter(&compBytes) + if _, err = compWriter.Write(res); err != nil { + _ = c.AbortWithError(http.StatusInternalServerError, err) + return + } + if err = compWriter.Close(); err != nil { + _ = c.AbortWithError(http.StatusInternalServerError, err) + return + } + + c.Header("Content-Encoding", "gzip") if c.Request.Method == http.MethodHead { - c.Header("Content-Length", strconv.Itoa(len(res))) + c.Header("Content-Length", strconv.Itoa(compBytes.Len())) c.Header("Content-Type", "application/xml") c.Status(http.StatusOK) } else { - c.Data(http.StatusOK, "application/xml", res) + c.Data(http.StatusOK, "application/xml", compBytes.Bytes()) } }