-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
zstd.go
41 lines (32 loc) · 976 Bytes
/
zstd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"io"
"net/http"
"strings"
"github.com/klauspost/compress/zstd"
)
type zstdResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w zstdResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
// zstdMiddleware applies zstd compression to HTTP responses.
func zstdMiddleware(next http.Handler, compressionLevel int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "zstd") {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "zstd")
encoder, err := zstd.NewWriter(w, zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(compressionLevel)))
if err != nil {
http.Error(w, "Failed to create zstd encoder", http.StatusInternalServerError)
return
}
defer encoder.Close()
compressedWriter := zstdResponseWriter{Writer: encoder, ResponseWriter: w}
next.ServeHTTP(compressedWriter, r)
})
}