json - gzip 压缩到 http responseWriter

标签 json rest http go gzip

我是 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/

相关文章:

java - 模拟方法,但它调用实际方法

json - 限制 Json 模式中的返回字段

asp.net-mvc - 创建 RESTful 架构以使用 JSON 在 ASP.NET Web 应用程序和 MVC 3 应用程序之间进行通信

xml - 为什么 curl 在 HTTP PUT 中的消息正文之前发送命令行?

java - MailChimp 3.0 HTTP POST Json 示例

c++ - native IIS7.5 模块未运行

mysql - 如何使用 sqoop 将 JSON 字段数据从 mySql 服务器导入到 Hive 表中

java - org.json.JSONException 值 java.lang.String 类型的连接无法转换为 JSONArray

rest - Docker API 返回 200 OK 然后 400 BAD REQUEST

java - 匿名上传文件对象到 Imgur API (JSON) 给出身份验证错误 401