feat(dict): 添加字典数据压缩加密功能 - 在字典数据接口中集成压缩和加密机制 - 实现Gzip压缩、XOR加密和Base64编码流程 - 新增CompressAndEncrypt和DecryptAndDecompress工具函数 - 在middleware中启用压缩中间件支持 ```
This commit is contained in:
70
modules/base/middleware/gzib.go
Normal file
70
modules/base/middleware/gzib.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"strings"
|
||||
|
||||
"github.com/andybalholm/brotli"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
func CompressMiddleware(r *ghttp.Request) {
|
||||
ae := strings.ToLower(r.Header.Get("Accept-Encoding"))
|
||||
|
||||
// 先执行后面的逻辑
|
||||
r.Middleware.Next()
|
||||
|
||||
// 已经压缩过就跳过
|
||||
if r.Response.Header().Get("Content-Encoding") != "" {
|
||||
return
|
||||
}
|
||||
|
||||
// 只压缩文本类型
|
||||
contentType := r.Response.Header().Get("Content-Type")
|
||||
compressTypes := []string{
|
||||
"text/",
|
||||
"application/json",
|
||||
"application/javascript",
|
||||
"application/xml",
|
||||
}
|
||||
need := false
|
||||
for _, t := range compressTypes {
|
||||
if strings.HasPrefix(contentType, t) {
|
||||
need = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !need {
|
||||
return
|
||||
}
|
||||
|
||||
buf := r.Response.Buffer()
|
||||
if len(buf) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// 优先 Brotli
|
||||
if strings.Contains(ae, "br") {
|
||||
r.Response.Header().Set("Content-Encoding", "br")
|
||||
r.Response.Header().Del("Content-Length")
|
||||
r.Response.ClearBuffer()
|
||||
|
||||
wr := brotli.NewWriterLevel(r.Response.Writer, brotli.BestCompression)
|
||||
defer wr.Close()
|
||||
wr.Write(buf)
|
||||
return
|
||||
}
|
||||
|
||||
// 降级 Gzip
|
||||
if strings.Contains(ae, "gzip") {
|
||||
r.Response.Header().Set("Content-Encoding", "gzip")
|
||||
r.Response.Header().Del("Content-Length")
|
||||
r.Response.ClearBuffer()
|
||||
|
||||
wr, _ := gzip.NewWriterLevel(r.Response.Writer, flate.BestCompression)
|
||||
defer wr.Close()
|
||||
wr.Write(buf)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func init() {
|
||||
tt.ServeHTTP(r.Response.Writer, r.Request)
|
||||
|
||||
})
|
||||
|
||||
g.Server().Use(CompressMiddleware)
|
||||
g.Server().BindHandler("/server/*", func(r *ghttp.Request) {
|
||||
servert := new(ServerHandler)
|
||||
id := gconv.Uint16(r.URL.Query().Get("id"))
|
||||
|
||||
Reference in New Issue
Block a user