gzip.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package httptoo
  2. import (
  3. "compress/gzip"
  4. "io"
  5. "net/http"
  6. "strings"
  7. )
  8. type gzipResponseWriter struct {
  9. io.Writer
  10. http.ResponseWriter
  11. haveWritten bool
  12. }
  13. var _ http.ResponseWriter = &gzipResponseWriter{}
  14. func (w *gzipResponseWriter) Write(b []byte) (int, error) {
  15. if w.haveWritten {
  16. goto write
  17. }
  18. w.haveWritten = true
  19. if w.Header().Get("Content-Type") != "" {
  20. goto write
  21. }
  22. if type_ := http.DetectContentType(b); type_ != "application/octet-stream" {
  23. w.Header().Set("Content-Type", type_)
  24. }
  25. write:
  26. return w.Writer.Write(b)
  27. }
  28. // Gzips response body if the request says it'll allow it.
  29. func GzipHandler(h http.Handler) http.Handler {
  30. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  31. if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") || w.Header().Get("Content-Encoding") != "" || w.Header().Get("Vary") != "" {
  32. h.ServeHTTP(w, r)
  33. return
  34. }
  35. w.Header().Set("Content-Encoding", "gzip")
  36. w.Header().Set("Vary", "Accept-Encoding")
  37. gz := gzip.NewWriter(w)
  38. defer gz.Close()
  39. h.ServeHTTP(&gzipResponseWriter{
  40. Writer: gz,
  41. ResponseWriter: w,
  42. }, r)
  43. })
  44. }