api: allow gzipped response

This commit is contained in:
Adhityaa 2018-06-11 15:01:58 +05:30
parent 9e682a964a
commit 78384073b0
4 changed files with 46 additions and 6 deletions

View File

@ -24,6 +24,8 @@ func parseConfig() error {
"STATIC": binPath,
"GZIP_STATIC": "false",
"SMTP_USERNAME": "",
"SMTP_PASSWORD": "",
"SMTP_HOST": "",

View File

@ -37,3 +37,4 @@ var errorSessionAlreadyInUse = errors.New("Session is already in use.")
var errorCannotReadResponse = errors.New("Cannot read response.")
var errorNotModerator = errors.New("You need to be a moderator to do that.")
var errorNotADirectory = errors.New("The given path is not a directory.")
var errorGzip = errors.New("Cannot GZip content.")

View File

@ -25,7 +25,8 @@ type staticHtmlPlugs struct {
}
func initStaticRouter(router *mux.Router) error {
asset := make(map[string]string)
asset := make(map[string][]byte)
gzippedAsset := make(map[string][]byte)
for _, dir := range []string{"js", "css", "images"} {
sl := string(os.PathSeparator)
@ -52,12 +53,30 @@ func initStaticRouter(router *mux.Router) error {
prefix += "window.commento_cdn='" + os.Getenv("CDN_PREFIX") + "';\n"
}
asset[p] = prefix + string(contents)
gzip := (os.Getenv("GZIP_STATIC") == "true")
asset[p] = []byte(prefix + string(contents))
if gzip {
gzippedAsset[p], err = gzipStatic(asset[p])
if err != nil {
logger.Errorf("error gzipping %s: %v", p, err)
return err
}
}
// faster than checking inside the handler
if !gzip {
router.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path)))
fmt.Fprint(w, asset[r.URL.Path])
w.Write(asset[r.URL.Path])
})
} else {
router.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", mime.TypeByExtension(path.Ext(r.URL.Path)))
w.Header().Set("Content-Encoding", "gzip")
w.Write(gzippedAsset[r.URL.Path])
})
}
}
}

18
api/utils_gzip.go Normal file
View File

@ -0,0 +1,18 @@
package main
import (
"bytes"
"compress/gzip"
)
func gzipStatic(b []byte) ([]byte, error) {
var buf bytes.Buffer
g := gzip.NewWriter(&buf)
if _, err := g.Write(b); err != nil {
g.Close()
return []byte{}, err
}
g.Close()
return buf.Bytes(), nil
}