gpt4 book ai didi

json - gzip 压缩到 http responseWriter

转载 作者:数据小太阳 更新时间:2023-10-29 03:05:50 26 4
gpt4 key购买 nike

我是 Go 的新手。但是我正在玩 REST Api。在我拥有的两个函数中,我无法从 json.Marshal 获得与 json.Encoder 相同的行为

我想使用这个函数来 gzip 我的回复:

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)

它工作正常。

最佳答案

我会避免手动 gzip-ing []byte。您可以轻松地使用标准库中已有的编写器。此外,看一下 compress/flate,我认为应该使用它来代替 gzip。

package main

import (
"net/http"
"encoding/json"
"compress/gzip"
"log"
)

type Box struct {
Width int `json:"width"`
}

func writeJsonResponseCompressed(w http.ResponseWriter, r *http.Request) {

box := &Box{Width: 10}

w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Encoding", "gzip")

body, err := json.Marshal(box)
if err != nil {
// Your error handling
return
}

writer, err := gzip.NewWriterLevel(w, gzip.BestCompression)
if err != nil {
// Your error handling
return
}

defer writer.Close()

writer.Write(body)
}

func main() {
http.HandleFunc("/compressedget", writeJsonResponseCompressed)
log.Fatal(http.ListenAndServe(":8081", nil))
}

关于json - gzip 压缩到 http responseWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39112912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com