doulin4844 2016-07-19 14:17
浏览 564

如何为Golang Gin框架返回gzip响应

I'm trying to return a gzip response using the golang framework gin.

They provide an example here: https://github.com/gin-gonic/contrib/blob/master/gzip/example/example.go

package main

import (
    "fmt"
    "github.com/gin-gonic/contrib/gzip"
    "github.com/gin-gonic/gin"
    "time"
)

func main() {
    r := gin.Default()
    r.Use(gzip.Gzip(gzip.DefaultCompression))
    r.GET("/ping", func(c *gin.Context) {
        c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
    })

    // Listen and Server in 0.0.0.0:8080
    r.Run(":8080")
}

When I use this example its not returning gzipped content.

With the code above I get the following output from curl

curl -v -H "Accept-Encoding: gzip" 'http://localhost:8080/ping'

Trying ::1...
Connected to localhost (::1) port 8080 (#0) GET /ping HTTP/1.1 Host: localhost:8080 User-Agent: curl/7.43.0 Accept: / Accept-Encoding: gzip
< HTTP/1.1 200 OK
< Content-Encoding: gzip
< Content-Type: text/plain; charset=utf-8
< Vary: Accept-Encoding
< Date: Mon, 18 Jul 2016 17:20:56 GMT
< Content-Length: 38
<

Connection #0 to host localhost left intact pong 1468862456?n????

Notice the content is not gzipped and there are extra junk characters added on.

"?n????"

So far I can't figure out how to get it to return gzip. I think there is a mistake in the example code but I'm having trouble figuring it out.

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • doulin1867 2016-07-19 17:23
    关注

    Someone else had an issue with gzip. Their pull request resolved this problem for me. It's a bug in the gzip package for gin framework.

    This method was missing from contrib/gzip/gzip.go

    func (g *gzipWriter) WriteString(s string) (n int, err error) {
        return g.writer.Write([]byte(s))
    }
    

    Link to original issue that includes pull request. https://github.com/gin-gonic/contrib/pull/59

    Once the owner of the project accepts the pull request this issue will be resolved.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号