mirror of
https://github.com/casdoor/casdoor.git
synced 2025-07-03 20:50:19 +08:00
feat: add gzip support for static filter (#1875)
* feat: add gzip support for static filter * Update static_filter.go --------- Co-authored-by: hsluoyz <hsluoyz@qq.com>
This commit is contained in:
@ -15,6 +15,8 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@ -28,6 +30,7 @@ import (
|
||||
var (
|
||||
oldStaticBaseUrl = "https://cdn.casbin.org"
|
||||
newStaticBaseUrl = conf.GetConfigString("staticBaseUrl")
|
||||
enableGzip, _ = conf.GetConfigBool("enableGzip")
|
||||
)
|
||||
|
||||
func StaticFilter(ctx *context.Context) {
|
||||
@ -53,7 +56,7 @@ func StaticFilter(ctx *context.Context) {
|
||||
|
||||
path2 := strings.TrimLeft(path, "web/build/images/")
|
||||
if util.FileExist(path2) {
|
||||
http.ServeFile(ctx.ResponseWriter, ctx.Request, path2)
|
||||
makeGzipResponse(ctx.ResponseWriter, ctx.Request, path2)
|
||||
return
|
||||
}
|
||||
|
||||
@ -62,7 +65,7 @@ func StaticFilter(ctx *context.Context) {
|
||||
}
|
||||
|
||||
if oldStaticBaseUrl == newStaticBaseUrl {
|
||||
http.ServeFile(ctx.ResponseWriter, ctx.Request, path)
|
||||
makeGzipResponse(ctx.ResponseWriter, ctx.Request, path)
|
||||
} else {
|
||||
serveFileWithReplace(ctx.ResponseWriter, ctx.Request, path, oldStaticBaseUrl, newStaticBaseUrl)
|
||||
}
|
||||
@ -89,3 +92,24 @@ func serveFileWithReplace(w http.ResponseWriter, r *http.Request, name string, o
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
type gzipResponseWriter struct {
|
||||
io.Writer
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
||||
return w.Writer.Write(b)
|
||||
}
|
||||
|
||||
func makeGzipResponse(w http.ResponseWriter, r *http.Request, path string) {
|
||||
if !enableGzip || !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
http.ServeFile(w, r, path)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
gz := gzip.NewWriter(w)
|
||||
defer gz.Close()
|
||||
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
|
||||
http.ServeFile(gzw, r, path)
|
||||
}
|
||||
|
Reference in New Issue
Block a user