improve (compression): on the fly gzip compression for a few endpoints

This commit is contained in:
Mickael Kerjean
2019-05-09 17:03:30 +10:00
parent d85bb41620
commit 8aa589b3d5
3 changed files with 24 additions and 7 deletions

View File

@ -1,6 +1,8 @@
package common
import (
"bytes"
"compress/gzip"
"encoding/json"
"net/http"
"strings"
@ -33,17 +35,32 @@ func SendSuccessResult(res http.ResponseWriter, data interface{}) {
encoder.Encode(APISuccessResult{"ok", data})
}
func SendSuccessResultWithEtag(res http.ResponseWriter, req *http.Request, data interface{}) {
json, _ := json.Marshal(APISuccessResult{"ok", data})
hash := QuickHash(string(json), 20)
func SendSuccessResultWithEtagAndGzip(res http.ResponseWriter, req *http.Request, data interface{}) {
dataToSend, _ := json.Marshal(APISuccessResult{"ok", data})
mode := "normal"
if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") == true {
mode = "gzip"
}
hash := QuickHash(mode + string(dataToSend), 20)
if req.Header.Get("If-None-Match") == hash {
res.WriteHeader(http.StatusNotModified)
return
}
res.Header().Set("Etag", hash)
res.Write(json)
head := res.Header()
head.Set("Etag", hash)
if mode == "gzip" {
head.Set("Content-Encoding", "gzip")
var b bytes.Buffer
w, _ := gzip.NewWriterLevel(&b, 1)
w.Write(dataToSend)
w.Close()
dataToSend = b.Bytes()
}
res.Write(dataToSend)
}
func SendSuccessResults(res http.ResponseWriter, data interface{}) {
encoder := json.NewEncoder(res)
encoder.SetEscapeHTML(false)

View File

@ -82,6 +82,6 @@ func AdminBackend(ctx App, res http.ResponseWriter, req *http.Request) {
for key := range drivers {
backends[key] = drivers[key].LoginForm()
}
SendSuccessResultWithEtag(res, req, backends)
SendSuccessResultWithEtagAndGzip(res, req, backends)
return
}

View File

@ -71,5 +71,5 @@ func PrivateConfigUpdateHandler(ctx App, res http.ResponseWriter, req *http.Requ
func PublicConfigHandler(ctx App, res http.ResponseWriter, req *http.Request) {
cfg := Config.Export()
SendSuccessResultWithEtag(res, req, cfg)
SendSuccessResultWithEtagAndGzip(res, req, cfg)
}