gpt4 book ai didi

go - 如何使用gzip压缩http.FileServer内容?

转载 作者:行者123 更新时间:2023-12-01 22:06:34 27 4
gpt4 key购买 nike

我使用http.FileServer作为静态服务器,但是我想使用gzip compress

现在的代码:

    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)
})

并且响应 header 包含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包?

谢谢

最佳答案

net/http没有内置的gzip传输,需要使用第三方库来实现。

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)
}

关于go - 如何使用gzip压缩http.FileServer内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61492152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com