api: allow gzipped response
This commit is contained in:
parent
9e682a964a
commit
78384073b0
@ -24,6 +24,8 @@ func parseConfig() error {
|
||||
|
||||
"STATIC": binPath,
|
||||
|
||||
"GZIP_STATIC": "false",
|
||||
|
||||
"SMTP_USERNAME": "",
|
||||
"SMTP_PASSWORD": "",
|
||||
"SMTP_HOST": "",
|
||||
|
@ -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.")
|
||||
|
@ -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
18
api/utils_gzip.go
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user