Skip to content

Commit

Permalink
Merge pull request #800 from trheyi/main
Browse files Browse the repository at this point in the history
Add option to disable Gzip compression for static files and update he…
  • Loading branch information
trheyi authored Nov 30, 2024
2 parents 2f88e5c + 2c5b323 commit d6f134f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
9 changes: 6 additions & 3 deletions service/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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 {
Expand All @@ -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()
Expand Down
7 changes: 7 additions & 0 deletions service/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
1 change: 1 addition & 0 deletions share/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Expand Down

0 comments on commit d6f134f

Please sign in to comment.