Skip to content

Instantly share code, notes, and snippets.

@r10r
Last active August 29, 2015 14:13
Show Gist options
  • Save r10r/a072170ac6133b9610c7 to your computer and use it in GitHub Desktop.
Save r10r/a072170ac6133b9610c7 to your computer and use it in GitHub Desktop.
On the fly GZIP encoding for static files with negroni GZIP handler.
package main
import (
"fmt"
"github.com/codegangsta/negroni"
"github.com/phyber/negroni-gzip/gzip"
"net/http"
)
func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
fmt.Println("right before -->")
// do some stuff before
next(rw, r)
// do some stuff after
fmt.Println("right after <--")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Hello World!")
})
// Create an empty instance with no middleware preconfigured.
n := negroni.New()
n.Use(negroni.NewLogger())
// Add the GZIP compression handler.
// Test with: curl -H "Accept-Encoding: gzip" -v localhost:3000/
n.Use(gzip.Gzip(gzip.DefaultCompression))
// Content produced by every handler after the GZIP handler is compressed.
// Serve static files from './public'
n.Use(negroni.NewStatic(http.Dir("public")))
n.Use(negroni.HandlerFunc(MyMiddleware))
// ... Add any other middlware here
// add the router as the last handler in the stack
n.UseHandler(mux)
n.Run(":3000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment