Created
February 9, 2015 16:53
-
-
Save olekukonko/aa6153ff5ac35e6293f8 to your computer and use it in GitHub Desktop.
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
// call this function from a http Handler Func, where data is the response object | |
// response will be compressed with gzip if requester accepts it | |
// browser should automatically decompress into valid json | |
func jsonResponseWriter(w http.ResponseWriter, r *http.Request, data interface{}) error { | |
var err error | |
var jsonData []byte | |
if jsonData, err = json.Marshal(data); err != nil { | |
return err | |
} | |
w.Header().Set("Content-Type", "application/json") | |
gzipOk := strings.Contains(fmt.Sprint(r.Header["Accept-Encoding"]), "gzip") | |
if gzipOk { | |
w.Header().Set(“Content-Encoding”, “gzip”) | |
var compressor *gzip.Writer | |
if compressor, err = gzip.NewWriterLevel(w, gzip.DefaultCompression); err != nil { | |
return err | |
} | |
if _, err = compressor.Write(jsonData); err != nil { | |
return err | |
} | |
if err = compressor.Close(); err != nil { | |
return err | |
} | |
} else { | |
if _, err = w.Write(jsonData); err != nil { | |
return err | |
} | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment