From cfe84bf67c3a81e3fd94484d736deaa23815073c Mon Sep 17 00:00:00 2001 From: Nova Kwok Date: Tue, 30 Jun 2020 17:58:58 +0800 Subject: [PATCH] Try add Etag on response by nova --- helper.go | 14 +++++++++++++- router.go | 8 ++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/helper.go b/helper.go index b17a143..5125b76 100644 --- a/helper.go +++ b/helper.go @@ -2,11 +2,14 @@ package main import ( "fmt" - log "github.com/sirupsen/logrus" + "hash/crc32" + "io/ioutil" "net/http" "os" "path" "path/filepath" + + log "github.com/sirupsen/logrus" "strings" ) @@ -61,6 +64,15 @@ func GenWebpAbs(RawImagePath string, ExhaustPath string, ImgFilename string, req return cwd, WebpAbsolutePath } +func GenEtag(ImgAbsPath string) string { + data, err := ioutil.ReadFile(ImgAbsPath) + if err != nil { + log.Info(err) + } + crc := crc32.ChecksumIEEE(data) + return fmt.Sprintf(`W/"%d-%08X"`, len(data), crc) +} + func goOrigin(UA string) bool { // for more information, please check test case if strings.Contains(UA, "Firefox") || strings.Contains(UA, "Chrome") { diff --git a/router.go b/router.go index ef0788d..f0183ee 100644 --- a/router.go +++ b/router.go @@ -23,6 +23,10 @@ func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY done := goOrigin(UA) if done { log.Infof("A Safari/IE/whatever user has arrived...%s", UA) + // Check for Safari users. If they're Safari, just simply ignore everything. + + etag := GenEtag(RawImageAbs) + c.Set("ETag", etag) c.SendFile(RawImageAbs) return } @@ -46,6 +50,8 @@ func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY log.Warn(msg) c.Send(msg) if ImageExists(RawImageAbs) { + etag := GenEtag(RawImageAbs) + c.Set("ETag", etag) c.SendFile(RawImageAbs) } return @@ -95,6 +101,8 @@ func Convert(ImgPath string, ExhaustPath string, AllowedTypes []string, QUALITY } finalFile = WebpAbsPath } + etag := GenEtag(finalFile) + c.Set("ETag", etag) c.SendFile(finalFile) } }