Fix static path not changed bug in makeGzipResponse()

This commit is contained in:
Yang Luo
2023-07-29 12:23:48 +08:00
parent a38896e4d8
commit 6c628d7893

View File

@@ -68,11 +68,11 @@ func StaticFilter(ctx *context.Context) {
if oldStaticBaseUrl == newStaticBaseUrl { if oldStaticBaseUrl == newStaticBaseUrl {
makeGzipResponse(ctx.ResponseWriter, ctx.Request, path) makeGzipResponse(ctx.ResponseWriter, ctx.Request, path)
} else { } else {
serveFileWithReplace(ctx.ResponseWriter, ctx.Request, path, oldStaticBaseUrl, newStaticBaseUrl) serveFileWithReplace(ctx.ResponseWriter, ctx.Request, path)
} }
} }
func serveFileWithReplace(w http.ResponseWriter, r *http.Request, name string, old string, new string) { func serveFileWithReplace(w http.ResponseWriter, r *http.Request, name string) {
f, err := os.Open(filepath.Clean(name)) f, err := os.Open(filepath.Clean(name))
if err != nil { if err != nil {
panic(err) panic(err)
@@ -85,13 +85,9 @@ func serveFileWithReplace(w http.ResponseWriter, r *http.Request, name string, o
} }
oldContent := util.ReadStringFromPath(name) oldContent := util.ReadStringFromPath(name)
newContent := strings.ReplaceAll(oldContent, old, new) newContent := strings.ReplaceAll(oldContent, oldStaticBaseUrl, newStaticBaseUrl)
http.ServeContent(w, r, d.Name(), d.ModTime(), strings.NewReader(newContent)) http.ServeContent(w, r, d.Name(), d.ModTime(), strings.NewReader(newContent))
_, err = w.Write([]byte(newContent))
if err != nil {
panic(err)
}
} }
type gzipResponseWriter struct { type gzipResponseWriter struct {
@@ -105,12 +101,12 @@ func (w gzipResponseWriter) Write(b []byte) (int, error) {
func makeGzipResponse(w http.ResponseWriter, r *http.Request, path string) { func makeGzipResponse(w http.ResponseWriter, r *http.Request, path string) {
if !enableGzip || !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { if !enableGzip || !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
http.ServeFile(w, r, path) serveFileWithReplace(w, r, path)
return return
} }
w.Header().Set("Content-Encoding", "gzip") w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w) gz := gzip.NewWriter(w)
defer gz.Close() defer gz.Close()
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w} gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
http.ServeFile(gzw, r, path) serveFileWithReplace(gzw, r, path)
} }