Created
January 19, 2015 08:43
-
-
Save mountkin/548dc9b41ca96019dabf to your computer and use it in GitHub Desktop.
Hack on go-bindata to support gzip Content-Encoding
This file contains 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 views | |
import ( | |
"bytes" | |
"compress/gzip" | |
"io" | |
"mime" | |
"net/http" | |
"path" | |
"strings" | |
) | |
type Views struct { | |
Names map[string]struct{} | |
Index string | |
} | |
func New(fallback string) *Views { | |
v := &Views{make(map[string]struct{}), fallback} | |
names := AssetNames() | |
for _, n := range names { | |
v.Names[n] = struct{}{} | |
} | |
return v | |
} | |
func (v *Views) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
var ok bool | |
name := r.URL.Path[1:] | |
if _, ok = v.Names[name]; !ok { | |
name = v.Index | |
} | |
ext := path.Ext(name) | |
ct := mime.TypeByExtension(ext) | |
w.Header().Set("Content-Type", ct) | |
data, _ := Asset(name) | |
hdr := r.Header.Get("Accept-Encoding") | |
if strings.Contains(hdr, "gzip") { | |
w.Header().Set("Content-Encoding", "gzip") | |
w.Write(data) | |
} else { | |
gz, err := gzip.NewReader(bytes.NewBuffer(data)) | |
if err != nil { | |
w.Write([]byte(err.Error())) | |
return | |
} | |
io.Copy(w, gz) | |
gz.Close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment