-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathetag.go
56 lines (46 loc) · 1.09 KB
/
etag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package etag
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
const (
ETag = "ETag"
CacheControl = "Cache-Control"
IfNoneMatch = "If-None-Match"
MaxAge = "max-age"
)
func HttpEtagCache(maxAge uint) gin.HandlerFunc {
return func(c *gin.Context) {
w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
c.Writer = w
c.Next()
eTag := generateMD5Hash(w.body.String())
w.ResponseWriter.Header().Set(ETag, eTag)
if len(c.Request.Header.Get(IfNoneMatch)) > 0 {
if eTag == c.Request.Header.Get(IfNoneMatch) {
c.Writer.Header().Set(CacheControl, fmt.Sprintf("%s=%d", MaxAge, maxAge))
c.Status(http.StatusNotModified)
return
}
}
_, err := w.ResponseWriter.Write(w.body.Bytes())
if err != nil {
panic(err)
}
}
}
func generateMD5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (r responseBodyWriter) Write(b []byte) (int, error) {
return r.body.Write(b)
}