亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 gzip 壓縮 http.FileServer 內容?

如何使用 gzip 壓縮 http.FileServer 內容?

Go
冉冉說 2022-06-01 15:24:28
我使用 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)    })并且響應標頭已包含 gzipHTTP/1.1 200 OKAccept-Ranges: bytesContent-Encoding: gzipContent-Type: text/html; charset=utf-8Last-Modified: Tue, 28 Apr 2020 12:06:15 GMTDate: Tue, 28 Apr 2020 16:39:40 GMTContent-Length: 687那么這里如何使用 gzip 包呢?
查看完整描述

2 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

沒有內置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)

}


查看完整回答
反對 回復 2022-06-01
?
呼如林

TA貢獻1798條經驗 獲得超3個贊

我根據the42 CJEnright的各種要點整理了這段代碼


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(`.`))))

}



查看完整回答
反對 回復 2022-06-01
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號