Created
November 5, 2016 05:16
-
-
Save xDarkicex/ccc714cd0a91bad29a499fe15becf3a4 to your computer and use it in GitHub Desktop.
Example of caching and gzip, httprouter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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