json - gzip compression to http responseWriter -


i'm new go. playing rest api. cant same behavior out of json.marshal json.encoder in 2 functions have

i wanted use function gzip responses:

func gzipfast(a *[]byte) []byte {     var b bytes.buffer     gz := gzip.newwriter(&b)     defer gz.close()     if _, err := gz.write(*a); err != nil {         panic(err)     }     return b.bytes() } 

but function returns this:

curl http://localhost:8081/compressedget --compressed --verbose *   trying 127.0.0.1... * connected localhost (127.0.0.1) port 8081 (#0) > /compressedget http/1.1 > host: localhost:8081 > user-agent: curl/7.47.0 > accept: */* > accept-encoding: deflate, gzip >  < http/1.1 200 ok < content-encoding: gzip < content-type: application/json < date: wed, 24 aug 2016 00:59:38 gmt < content-length: 30 <  * connection #0 host localhost left intact 

here go function:

func compressedget(w http.responsewriter, r *http.request, ps  httprouter.params) {      box := box{width: 10, height: 20, color: "gree", open: false}     box.ars = make([]int, 100)     := range box.ars {         box.ars[i] =     }     //fmt.println(r.header.get("content-encoding"))      w.header().set("content-type", "application/json")     w.header().set("content-encoding", "gzip")     b, _ := json.marshal(box)     //fmt.println(len(b))     //fmt.println(len(gzipfast(&b)))      fmt.fprint(w, gzipfast(&b))     //fmt.println(len(gzipslow(b)))     //gz := gzip.newwriter(w)     //defer gz.close()     //json.newencoder(gz).encode(box)     r.body.close()  } 

but when uncomment:

//gz := gzip.newwriter(w) //defer gz.close() //json.newencoder(gz).encode(box) 

it works fine.

you need flush or close gzip writer before accessing underlying bytes, e.g.

func gzipfast(a *[]byte) []byte {     var b bytes.buffer     gz := gzip.newwriter(&b)     if _, err := gz.write(*a); err != nil {         gz.close()         panic(err)     }     gz.close()     return b.bytes() } 

otherwise what's been buffer in gzip writer, not yet written out final stream isn't getting collected up.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -