Skip to content

Instantly share code, notes, and snippets.

@xDarkicex
Created November 5, 2016 05:16
Show Gist options
  • Save xDarkicex/ccc714cd0a91bad29a499fe15becf3a4 to your computer and use it in GitHub Desktop.
Save xDarkicex/ccc714cd0a91bad29a499fe15becf3a4 to your computer and use it in GitHub Desktop.
Example of caching and gzip, httprouter
package gzip
import (
"compress/gzip"
"io"
"net/http"
"strings"
"github.com/julienschmidt/httprouter"
)
// GzipResponseWriter is a Struct for manipulating io writer
type GzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (res GzipResponseWriter) Write(b []byte) (int, error) {
if "" == res.Header().Get("Content-Type") {
// If no content type, apply sniffing algorithm to un-gzipped body.
res.Header().Set("Content-Type", http.DetectContentType(b))
}
return res.Writer.Write(b)
}
// Middleware force - bool, whether or not to force Gzip regardless of the sent headers.
func Middleware(fn httprouter.Handle, force bool) httprouter.Handle {
return func(res http.ResponseWriter, req *http.Request, pm httprouter.Params) {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") && !force {
fn(res, req, pm)
return
}
res.Header().Set("Vary", "Accept-Encoding")
res.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(res)
defer gz.Close()
gzr := GzipResponseWriter{Writer: gz, ResponseWriter: res}
fn(gzr, req, pm)
}
}
func GetRoutes() *httprouter.Router {
router := httprouter.New()
///////////////////////////////////////////////////////////
// Main application routes
///////////////////////////////////////////////////////////
application := controllers.Application{}
router.GET("/", gzip.Middleware(application.Index, false))
///////////////////////////////////////////////////////////
// Static routes
// Caching Static files
///////////////////////////////////////////////////////////
fileServer := http.FileServer(http.Dir("public"))
router.GET("/static/*filepath", func(res http.ResponseWriter, req *http.Request, pm httprouter.Params) {
res.Header().Set("Vary", "Accept-Encoding")
res.Header().Set("Cache-Control", "public, max-age=7776000")
req.URL.Path = pm.ByName("filepath")
fileServer.ServeHTTP(res, req)
})
return router
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment