go - 如何使用 gzip 压缩 http.FileServer 内容?
问题描述
我使用 http.FileServer 作为静态服务器,但我想使用 gzip 压缩
现在的代码:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Static file route
handle := http.FileServer(http.Dir("resource/dist"))
w.Header().Set("Content-Encoding", "gzip")
// ??? use gzip here?
handle.ServeHTTP(w, r)
})
并且响应标头已包含 gzip
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Last-Modified: Tue, 28 Apr 2020 12:06:15 GMT
Date: Tue, 28 Apr 2020 16:39:40 GMT
Content-Length: 687
那么这里如何使用 gzip 包呢?
谢谢
解决方案
没有内置gzip传输net/http
,需要使用第三方库实现。
https://github.com/nytimes/gziphandler
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)
}
推荐阅读
- spring-boot - 需要在 Spring Boot 中动态生成 url 以进行招摇
- javascript - 如何确定 jquery ajax 调用何时完成?
- sql - 将数值转换为 VARCHAR2 会引发 ORA-03113
- teradata - 如何检查 Teradata 中的列是 CASESPECIFIC 还是 NOT CASESPECIFIC
- vue.js - Vue v-model 命名最佳实践
- python - spaCy中的token和span(来自文档的切片)有什么区别?
- java - Java Spark获取kafka解析json
- ssl - WebSocket 握手:意外的响应代码:200 - React 客户端
- python - Python datetime.datetime 不在 pandas._libs.tslibs.timestamps.Timestamp 系列中
- stm32 - STM32 Nucleo F103RB:LD1 使用外部电源缓慢闪烁