gzip icon indicating copy to clipboard operation
gzip copied to clipboard

Static content under public/ with martini.Classic() will not get compressed

Open djhworld opened this issue 9 years ago • 2 comments

I've noticed this on my machine, using the example in the README

func main() {
  m := martini.Classic()
  // gzip every request
  m.Use(gzip.All())
  m.Run()
}

All requests after the line m.Use(gzip.All()) will be compressed with gzip (assuming the HTTP request has the correct header) - this is correct as per the requirement in the README Make sure to include the Gzip middleware above other middleware that alter the response body

However, if you have static content under public, none of that will be gzipped. This is because the martini.Classic constructs its handler for static content within the Classic() constructor (see https://github.com/go-martini/martini/blob/master/martini.go#L112), crucially this is before we add our gzip handler.

There are a few ways to resolve this

  1. Store all static content you want to be gzipped in a different folder and then add m.Use(martini.Static("myfolder")) in your code.
  2. Create a new function ClassicGzipped (this is my current approach) that has all the handlers from martini.Classic() but puts the line m.Use(gzip.All()) first, e.g.
    func ClassicGzipped() *martini.ClassicMartini {
        r := NewRouter()
        m := New()
        m.Use(Logger())
        m.Use(Recovery())
        //gzip all requests, including content under public/
        m.Use(gzip.All())
        m.Use(Static("public"))
        m.MapTo(r, (*Routes)(nil))
        m.Action(r.Handle)
        return &ClassicMartini{m, r}
    }

This isn't really a bug, but just an observation - if we agree I'm happy to update the README detailing this gotcha?

djhworld avatar Aug 07 '14 12:08 djhworld