GoBlog/cacheRecorder.go

65 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-02-21 17:47:41 +00:00
package main
import (
2023-04-11 14:43:14 +00:00
"crypto/sha256"
"fmt"
2022-02-21 17:47:41 +00:00
"net/http"
)
// cacheRecorder is an implementation of http.ResponseWriter
type cacheRecorder struct {
item cacheItem
done bool
2022-02-21 17:47:41 +00:00
}
func newCacheRecorder() *cacheRecorder {
return &cacheRecorder{
item: cacheItem{
2022-02-21 17:47:41 +00:00
code: http.StatusOK,
header: http.Header{},
2022-02-21 17:47:41 +00:00
},
}
}
func (c *cacheRecorder) finish() *cacheItem {
c.done = true
2023-04-11 14:43:14 +00:00
c.item.eTag = c.item.header.Get("ETag")
if c.item.eTag == "" {
c.item.eTag = fmt.Sprintf("%x", sha256.Sum256(c.item.body))
}
return &c.item
2022-02-21 17:47:41 +00:00
}
// Header implements http.ResponseWriter.
func (c *cacheRecorder) Header() http.Header {
if c.done {
2022-02-21 17:47:41 +00:00
return nil
}
return c.item.header
2022-02-21 17:47:41 +00:00
}
// Write implements http.ResponseWriter.
func (c *cacheRecorder) Write(buf []byte) (int, error) {
if c.done {
2022-02-21 17:47:41 +00:00
return 0, nil
}
c.item.body = append(c.item.body, buf...)
2022-02-21 17:47:41 +00:00
return len(buf), nil
}
// WriteString implements io.StringWriter.
func (c *cacheRecorder) WriteString(str string) (int, error) {
if c.done {
return 0, nil
}
return c.Write([]byte(str))
2022-02-21 17:47:41 +00:00
}
// WriteHeader implements http.ResponseWriter.
func (c *cacheRecorder) WriteHeader(code int) {
if c.done {
2022-02-21 17:47:41 +00:00
return
}
c.item.code = code
2022-02-21 17:47:41 +00:00
}