使用 Gzip 头实现文件强制下载
积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《使用 Gzip 头实现文件强制下载》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
我正在尝试压缩所有回复。 在main.go中
mux := mux.newrouter() mux.use(middlewareheaders) mux.use(gziphandler)
然后我有中间件:
func gziphandler(next http.handler) http.handler { return http.handlerfunc(func(w http.responsewriter, r *http.request) { gz := gzip.newwriter(w) defer gz.close() gzr := gzipresponsewriter{writer: gz, responsewriter: w} next.servehttp(gzr, r) }) } func middlewareheaders(next http.handler) http.handler { return http.handlerfunc(func(w http.responsewriter, r *http.request) { w.header().set("cache-control", "max-age=2592000") // 30 days w.header().set("content-encoding", "gzip") w.header().set("strict-transport-security", "max-age=63072000; includesubdomains; preload") w.header().set("access-control-allow-headers", "content-type,x-amz-date,authorization,x-api-key,x-amz-security-token") w.header().set("access-control-allow-methods", "post") w.header().set("access-control-allow-origin", "origin") w.header().set("access-control-allow-credentials", "true") w.header().set("access-control-expose-headers", "amp-access-control-allow-source-origin") w.header().set("amp-access-control-allow-source-origin", os.getenv("domain")) next.servehttp(w, r) }) }
当我卷曲网站时,我得到
curl -v https://example.com * Trying 44.234.222.27:443... * TCP_NODELAY set * Connected to example.com (XX.XXX.XXX.XX) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs * TLSv1.3 (OUT), TLS handshake, Client hello (1): * TLSv1.3 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256 * ALPN, server accepted to use h2 * Server certificate: * subject: CN=example.com * start date: Mar 16 00:00:00 2021 GMT * expire date: Apr 16 23:59:59 2022 GMT * subjectAltName: host "example.com" matched cert's "example.com" * issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA * SSL certificate verify ok. * Using HTTP2, server supports multi-use * Connection state changed (HTTP/2 confirmed) * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0 * Using Stream ID: 1 (easy handle 0x55cadcebfe10) > GET / HTTP/2 > Host: example.com > user-agent: curl/7.68.0 > accept: */* > * Connection state changed (MAX_CONCURRENT_STREAMS == 128)! < HTTP/2 200 < date: Mon, 07 Jun 2021 20:13:19 GMT < access-control-allow-credentials: true < access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token < access-control-allow-methods: POST < access-control-allow-origin: origin < access-control-expose-headers: AMP-Access-Control-Allow-Source-Origin < amp-access-control-allow-source-origin: example.com < cache-control: max-age=2592000 < content-encoding: gzip < strict-transport-security: max-age=63072000; includeSubDomains; preload < vary: Accept-Encoding < Warning: Binary output can mess up your terminal. Use "--output -" to tell Warning: curl to output it to your terminal anyway, or consider "--output Warning:" to save to a file. * Failed writing body (0 != 3506) * stopped the pause stream! * Connection #0 to host example.com left intact
启用 gzip 处理程序和 gzip 标头时,浏览器想要下载文件。
有人能发现我的错误吗?
正确答案
1.仅当客户端请求时,您才应使用 gzip
。
accept-encoding:从来没有请求过 gzip
,但你还是 gzip
响应。
所以 curl
按原样将其返回给您。
2.考虑到浏览器的行为,这听起来像是双重压缩。也许您有一些 http 反向代理,它已经处理浏览器的压缩,但不压缩后端流量。因此,您可能根本不需要在后端进行任何 gzipping - 尝试 curl --compressed
来确认这一点。
3.您应该从响应中过滤掉 content-length
。 content-length是压缩后的http响应的最终大小,因此该值在压缩过程中会发生变化。
4.您不应该盲目地对所有 uri 应用压缩。一些处理程序已经执行 gzip 压缩(例如 prometheus /metrics
),而有些处理程序则毫无意义进行压缩(例如 .png
、.zip
、.gz
)。至少在将 accept-encoding: gzip
从请求中删除,然后再将其传递到处理程序链,以避免双重 gzipping。
5. go 中的透明 gzipping 之前已经实现过。快速搜索显示 this gist(根据上面第 4 点进行调整):
package main import ( "compress/gzip" "io" "io/ioutil" "net/http" "strings" "sync" ) var gzPool = sync.Pool{ New: func() interface{} { w := gzip.NewWriter(ioutil.Discard) return w }, } type gzipResponseWriter struct { io.Writer http.ResponseWriter } func (w *gzipResponseWriter) WriteHeader(status int) { w.Header().Del("Content-Length") w.ResponseWriter.WriteHeader(status) } func (w *gzipResponseWriter) Write(b []byte) (int, error) { return w.Writer.Write(b) } func Gzip(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { next.ServeHTTP(w, r) return } w.Header().Set("Content-Encoding", "gzip") gz := gzPool.Get().(*gzip.Writer) defer gzPool.Put(gz) gz.Reset(w) defer gz.Close() r.Header.Del("Accept-Encoding") next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r) }) }
注意 - 以上不支持分块编码和预告片。因此仍有改进的机会。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 Gzip 头实现文件强制下载》文章吧,也可关注golang学习网公众号了解相关技术文章。

- 上一篇
- 消除 if 语句中的否定形式

- 下一篇
- 如何访问 M 列表中的元素
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 可图AI图片生成
- 探索快手旗下可灵AI2.0发布的可图AI2.0图像生成大模型,体验从文本生成图像、图像编辑到风格转绘的全链路创作。了解其技术突破、功能创新及在广告、影视、非遗等领域的应用,领先于Midjourney、DALL-E等竞品。
- 11次使用
-
- MeowTalk喵说
- MeowTalk喵说是一款由Akvelon公司开发的AI应用,通过分析猫咪的叫声,帮助主人理解猫咪的需求和情感。支持iOS和Android平台,提供个性化翻译、情感互动、趣味对话等功能,增进人猫之间的情感联系。
- 11次使用
-
- Traini
- SEO摘要Traini是一家专注于宠物健康教育的创新科技公司,利用先进的人工智能技术,提供宠物行为解读、个性化训练计划、在线课程、医疗辅助和个性化服务推荐等多功能服务。通过PEBI系统,Traini能够精准识别宠物狗的12种情绪状态,推动宠物与人类的智能互动,提升宠物生活质量。
- 11次使用
-
- 可图AI 2.0图片生成
- 可图AI 2.0 是快手旗下的新一代图像生成大模型,支持文本生成图像、图像编辑、风格转绘等全链路创作需求。凭借DiT架构和MVL交互体系,提升了复杂语义理解和多模态交互能力,适用于广告、影视、非遗等领域,助力创作者高效创作。
- 16次使用
-
- 毕业宝AIGC检测
- 毕业宝AIGC检测是“毕业宝”平台的AI生成内容检测工具,专为学术场景设计,帮助用户初步判断文本的原创性和AI参与度。通过与知网、维普数据库联动,提供全面检测结果,适用于学生、研究者、教育工作者及内容创作者。
- 28次使用
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览