Add option to disable Gzip compression for static files and update headers

This commit is contained in:
Max 2024-11-30 18:23:21 +08:00
parent 1d414bceb8
commit 2c5b323d7d
3 changed files with 14 additions and 3 deletions

View file

@ -3,12 +3,14 @@ package service
import (
"bytes"
"compress/gzip"
"fmt"
"net/http"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/yao/share"
"github.com/yaoapp/yao/sui/api"
)
@ -88,8 +90,8 @@ func withStaticFileServer(c *gin.Context) {
return
}
// Gzip Compression
if strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
// Gzip Compression option
if share.App.Static.DisableGzip == false && strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := gz.Write([]byte(html)); err != nil {
@ -102,8 +104,9 @@ func withStaticFileServer(c *gin.Context) {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Header("Content-Length", fmt.Sprintf("%d", buf.Len()))
c.Header("Content-Type", "text/html; charset=utf-8")
c.Header("Accept-Ranges", "bytes")
c.Header("Content-Encoding", "gzip")
c.Data(http.StatusOK, "text/html", buf.Bytes())
c.Done()

View file

@ -35,6 +35,13 @@ type rewriteRule struct {
func SetupStatic() error {
setupAdminRoot()
setupRewrite()
// Disable gzip compression for static files
if share.App.Static.DisableGzip {
AppFileServer = http.FileServer(fs.Dir("public"))
return nil
}
AppFileServer = gzipHandler(http.FileServer(fs.Dir("public")))
return nil
}

View file

@ -98,6 +98,7 @@ type Moapi struct {
// Static setting
type Static struct {
DisableGzip bool `json:"disableGzip,omitempty"`
Rewrite []map[string]string `json:"rewrite,omitempty"`
SourceRoots map[string]string `json:"sourceRoots,omitempty"`
}