首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用gzip压缩http.FileServer内容?

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

Stack Overflow用户
提问于 2020-04-29 08:18:27
回答 2查看 386关注 0票数 0

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

现在的代码:

代码语言:javascript
复制
    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。

代码语言:javascript
复制
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包呢?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2020-04-29 09:28:54

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

https://github.com/nytimes/gziphandler

代码语言:javascript
复制
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)
}
票数 2
EN

Stack Overflow用户

发布于 2020-10-20 02:28:30

我根据the42 CJEnright的各种要点编写了这段代码

代码语言:javascript
复制
package main

import (
    "compress/gzip"
    "io"
    "io/ioutil"
    "net/http"
    "strings"
    "sync"
)

var gzPool = sync.Pool{
    New: func() interface{} {
        w := gzip.NewWriter(ioutil.Discard)
        gzip.NewWriterLevel(w, gzip.BestCompression)
        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)
}

// Gzip func handler
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()

       next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
    })
}

func main() {
    println("Starting on http://localhost:8080")
    http.ListenAndServe(":8080", Gzip(http.FileServer(http.Dir(`.`))))
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61492152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档