我是 Go 新手。但是我在玩 REST Api。在我拥有的两个函数中,我无法从 json.Marshal 中获得与 json.Encoder 相同的行为
我想用这个函数压缩我的回复:
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()
}
但是这个函数返回这个:
curl http://localhost:8081/compressedget --compressed --verbose
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8081 (#0)
> GET /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 to host localhost left intact
这是go函数:
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)
for i := range box.ars {
box.ars[i] = 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()
}
但是当我取消评论时:
//gz := gzip.NewWriter(w)
//defer gz.Close()
//json.NewEncoder(gz).Encode(box)
它工作正常。
心有法竹
凤凰求蛊
holdtom
相关分类