54 lines
1022 B
Go
Executable File
54 lines
1022 B
Go
Executable File
package gziphttp
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type GZipResponseWriter struct {
|
|
w http.ResponseWriter
|
|
gz *gzip.Writer
|
|
}
|
|
|
|
func Can(r *http.Request) bool {
|
|
if strings.HasSuffix(r.URL.Path, ".gz") {
|
|
return false
|
|
}
|
|
encodings, _ := r.Header["Accept-Encoding"]
|
|
for _, encoding := range encodings {
|
|
items := strings.Split(encoding, ",")
|
|
for _, item := range items {
|
|
if strings.TrimSpace(item) == "gzip" {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func New(w http.ResponseWriter) *GZipResponseWriter {
|
|
w.Header().Add("Content-Type", "text/html")
|
|
w.Header().Add("Content-Encoding", "gzip")
|
|
return &GZipResponseWriter{
|
|
w: w,
|
|
gz: gzip.NewWriter(w),
|
|
}
|
|
}
|
|
|
|
func (gz *GZipResponseWriter) Header() http.Header {
|
|
return gz.w.Header()
|
|
}
|
|
|
|
func (gz *GZipResponseWriter) WriteHeader(statusCode int) {
|
|
gz.w.WriteHeader(statusCode)
|
|
}
|
|
|
|
func (gz *GZipResponseWriter) Write(b []byte) (int, error) {
|
|
return gz.gz.Write(b)
|
|
}
|
|
|
|
func (gz *GZipResponseWriter) Close() error {
|
|
return gz.gz.Close()
|
|
}
|