Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving gzipped content for Go

Tags:

http

webserver

go

I'm starting to write server-side applications in Go. I'd like to use the Accept-Encoding request header to determine whether to compress the response entity using GZIP. I had hoped to find a way to do this directly using the http.Serve or http.ServeFile methods.

This is quite a general requirement; did I miss something or do I need to roll my own solution?

like image 541
Rick-777 Avatar asked Dec 28 '12 17:12

Rick-777


People also ask

How do I uncompress a gzipped HTTP response?

you need to unchank it. ... if ($chunked) $body=http_unchunk($body); if ($gzip) $body=gzdecode($body); if ($deflate) $body=gzdeflate($body); ...

What is content-Encoding gzip?

gzip. A format using the Lempel-Ziv coding (LZ77), with a 32-bit CRC. This is the original format of the UNIX gzip program. The HTTP/1.1 standard also recommends that the servers supporting this content-encoding should recognize x-gzip as an alias, for compatibility purposes. compress.

How do I enable gzip compression for HTML?

First, load the web page you want to check in your browser. Then, open the developer tools panel and select the Network tab. You'll see a list of all the resources sent by the web server (if not, you may need to reload the page).

How do I see gzip compression in Chrome?

Chrome changed the way it reports (see original answer if interested). You can tell using Developer Tools (F12). Go to the Network tab, select the file you want to examine and then look at the Headers tab on the right. If you are gzipped, then you will see that in the Content-Encoding.


2 Answers

The New York Times have released their gzip middleware package for Go.

You just pass your http.HandlerFunc through their GzipHandler and you're done. It looks like this:

package main  import (     "io"     "net/http"     "github.com/nytimes/gziphandler" )  func main() {     withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {         w.Header().Set("Content-Type", "text/plain")         io.WriteString(w, "Hello, World")     })      withGz := gziphandler.GzipHandler(withoutGz)      http.Handle("/", withGz)     http.ListenAndServe("0.0.0.0:8000", nil) } 
like image 109
Zippo Avatar answered Sep 22 '22 05:09

Zippo


There is no “out of the box” support for gzip-compressed HTTP responses yet. But adding it is pretty trivial. Have a look at

https://gist.github.com/the42/1956518

also

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/cgUp8_ATNtc

like image 21
rputikar Avatar answered Sep 22 '22 05:09

rputikar