Golang中如何启用压缩(gzip)功能

Golang中如何启用压缩(gzip)功能 如何在Go中实现gzip压缩?以下是我的代码:

https://play.golang.org/p/aJy5DvM_LQP

提前感谢

2 回复

Sibert:

如何在 Go 中实现 gzip?

看起来启用 gzip 的一种方式是使用 CDN。例如,CloudFlare 将此作为额外福利提供。https://gowebstatic.tk/cdn

但如果能了解是否以及如何在 Go 内部实现这一点,那将会很好。

更多关于Golang中如何启用压缩(gzip)功能的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go中启用gzip压缩可以通过标准库的compress/gzip包实现。以下是针对你代码的修改示例:

package main

import (
    "compress/gzip"
    "fmt"
    "io"
    "net/http"
    "strings"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    var writer io.Writer = w
    
    // 检查客户端是否支持gzip
    if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
        w.Header().Set("Content-Encoding", "gzip")
        gz := gzip.NewWriter(w)
        defer gz.Close()
        writer = gz
    }
    
    // 写入响应内容
    fmt.Fprintf(writer, "Hello, Gzipped World!")
}

对于静态文件服务器的gzip压缩:

func gzipHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
            h.ServeHTTP(w, r)
            return
        }
        
        w.Header().Set("Content-Encoding", "gzip")
        gz := gzip.NewWriter(w)
        defer gz.Close()
        
        grw := &gzipResponseWriter{Writer: gz, ResponseWriter: w}
        h.ServeHTTP(grw, r)
    })
}

type gzipResponseWriter struct {
    io.Writer
    http.ResponseWriter
}

func (grw gzipResponseWriter) Write(b []byte) (int, error) {
    return grw.Writer.Write(b)
}

// 使用方式
http.Handle("/", gzipHandler(http.FileServer(http.Dir("./static"))))

对于JSON API的压缩:

func jsonHandler(w http.ResponseWriter, r *http.Request) {
    data := map[string]interface{}{
        "message": "Hello World",
        "status":  "success",
    }
    
    var output io.Writer = w
    if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
        w.Header().Set("Content-Encoding", "gzip")
        gz := gzip.NewWriter(w)
        defer gz.Close()
        output = gz
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(output).Encode(data)
}

这些示例展示了在不同场景下如何实现gzip压缩响应。

回到顶部