修复WebP缓存长度可能不正确的问题

This commit is contained in:
刘祥超
2021-10-01 17:20:37 +08:00
parent 96c63300f4
commit b320d2dc58
2 changed files with 41 additions and 35 deletions

View File

@@ -193,6 +193,7 @@ func (this *HTTPRequest) doCacheRead() (shouldStop bool) {
this.writer.WriteHeader(http.StatusNotModified)
this.isCached = true
this.cacheRef = nil
this.writer.SetOk()
return true
}
@@ -203,6 +204,7 @@ func (this *HTTPRequest) doCacheRead() (shouldStop bool) {
this.writer.WriteHeader(http.StatusNotModified)
this.isCached = true
this.cacheRef = nil
this.writer.SetOk()
return true
}
@@ -349,7 +351,6 @@ func (this *HTTPRequest) doCacheRead() (shouldStop bool) {
}
} else { // 没有Range
this.writer.PrepareCompression(reader.BodySize())
this.writer.WriteHeader(reader.Status())
err = reader.ReadBody(buf, func(n int) (goNext bool, err error) {
@@ -370,5 +371,8 @@ func (this *HTTPRequest) doCacheRead() (shouldStop bool) {
this.isCached = true
this.cacheRef = nil
this.writer.SetOk()
return true
}

View File

@@ -240,6 +240,42 @@ func (this *HTTPWriter) SetOk() {
// Close 关闭
func (this *HTTPWriter) Close() {
// webp writer
if this.isOk && this.webpIsEncoding {
imageData, _, err := image.Decode(this.webpBuffer)
if err != nil {
_, _ = io.Copy(this.writer, this.webpBuffer)
// 处理缓存
if this.cacheWriter != nil {
_ = this.cacheWriter.Discard()
}
this.cacheWriter = nil
} else {
var f = types.Float32(this.req.web.WebP.Quality)
if f > 100 {
f = 100
}
this.webpIsWriting = true
err = webp.Encode(this, imageData, &webp.Options{
Lossless: false,
Quality: f,
Exact: true,
})
if err != nil {
if !this.req.canIgnore(err) {
remotelogs.Error("HTTP_WRITER", "encode webp failed: "+err.Error())
}
// 处理缓存
if this.cacheWriter != nil {
_ = this.cacheWriter.Discard()
}
this.cacheWriter = nil
}
}
}
// compression writer
if this.compressionWriter != nil {
if this.bodyCopying && this.compressionBodyWriter != nil {
@@ -281,40 +317,6 @@ func (this *HTTPWriter) Close() {
_ = this.cacheWriter.Discard()
}
}
// webp writer
if this.webpIsEncoding {
imageData, _, err := image.Decode(this.webpBuffer)
if err != nil {
_, _ = io.Copy(this.writer, this.webpBuffer)
// 处理缓存
if this.cacheWriter != nil {
_ = this.cacheWriter.Discard()
}
this.cacheWriter = nil
} else {
var f = types.Float32(this.req.web.WebP.Quality)
if f > 100 {
f = 100
}
this.webpIsWriting = true
err = webp.Encode(this, imageData, &webp.Options{
Lossless: false,
Quality: f,
Exact: true,
})
if err != nil {
remotelogs.Error("HTTP_WRITER", "encode webp failed: "+err.Error())
// 处理缓存
if this.cacheWriter != nil {
_ = this.cacheWriter.Discard()
}
this.cacheWriter = nil
}
}
}
}
// Hijack Hijack