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:
jump2cn
2023-05-22 22:40:46 +08:00
committed by GitHub
parent 47da3cdaa0
commit df61a536c1

View File

@ -15,6 +15,8 @@
package routers package routers
import ( import (
"compress/gzip"
"io"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@ -28,6 +30,7 @@ import (
var ( var (
oldStaticBaseUrl = "https://cdn.casbin.org" oldStaticBaseUrl = "https://cdn.casbin.org"
newStaticBaseUrl = conf.GetConfigString("staticBaseUrl") newStaticBaseUrl = conf.GetConfigString("staticBaseUrl")
enableGzip, _ = conf.GetConfigBool("enableGzip")
) )
func StaticFilter(ctx *context.Context) { func StaticFilter(ctx *context.Context) {
@ -53,7 +56,7 @@ func StaticFilter(ctx *context.Context) {
path2 := strings.TrimLeft(path, "web/build/images/") path2 := strings.TrimLeft(path, "web/build/images/")
if util.FileExist(path2) { if util.FileExist(path2) {
http.ServeFile(ctx.ResponseWriter, ctx.Request, path2) makeGzipResponse(ctx.ResponseWriter, ctx.Request, path2)
return return
} }
@ -62,7 +65,7 @@ func StaticFilter(ctx *context.Context) {
} }
if oldStaticBaseUrl == newStaticBaseUrl { if oldStaticBaseUrl == newStaticBaseUrl {
http.ServeFile(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, oldStaticBaseUrl, newStaticBaseUrl)
} }
@ -89,3 +92,24 @@ func serveFileWithReplace(w http.ResponseWriter, r *http.Request, name string, o
panic(err) 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)
}