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

问题描述 投票:0回答:1

我使用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包呢?

谅谅

go gzip
1个回答
2
投票

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

https:/github.comnytimesgziphandler。

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.