http - 为 Go 提供 gzip 压缩的内容

标签 http webserver go

我开始用 Go 编写服务器端应用程序。我想使用 Accept-Encoding 请求 header 来确定是否使用 GZIP 压缩响应实体。我曾希望找到一种直接使用 http.Servehttp.ServeFile 方法的方法。

这是一个相当普遍的要求;我错过了什么还是需要推出自己的解决方案?

最佳答案

《纽约时报》发布了他们的gzip middleware package for Go .

您只需通过他们的 GzipHandler 传递您的 http.HandlerFunc 即可。它看起来像这样:

package main

import (
    "io"
    "net/http"
    "github.com/nytimes/gziphandler"
)

func main() {
    withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain")
        io.WriteString(w, "Hello, World")
    })

    withGz := gziphandler.GzipHandler(withoutGz)

    http.Handle("/", withGz)
    http.ListenAndServe("0.0.0.0:8000", nil)
}

关于http - 为 Go 提供 gzip 压缩的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073393/

相关文章:

xml - 在 Golang 中解析 XML

json - 如何为 POST 请求创建 json 负载?

REST Api 端点获取多个资源

json - 如何在 GET 请求中发送结构

适用于 WAMP 本地主机但不适用于 WebServer 的 PHP 代码

unit-testing - 在 Go 中模拟非接口(interface)类型

go - 在 golang 的单独端口中公开 Prometheus 指标

http - UIWebView 和 HTTP Basic Auth 的问题

tomcat - 如何管理在 web 服务器上运行的 java 线程?

amazon-web-services - 亚马逊网络服务 - beantalk 定价决策