gunziphandler.go 512 B

123456789101112131415161718192021222324252627
  1. package handler
  2. import (
  3. "compress/gzip"
  4. "net/http"
  5. "strings"
  6. "github.com/tal-tech/go-zero/rest/httpx"
  7. )
  8. const gzipEncoding = "gzip"
  9. func GunzipHandler(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. if strings.Contains(r.Header.Get(httpx.ContentEncoding), gzipEncoding) {
  12. reader, err := gzip.NewReader(r.Body)
  13. if err != nil {
  14. w.WriteHeader(http.StatusBadRequest)
  15. return
  16. }
  17. r.Body = reader
  18. }
  19. next.ServeHTTP(w, r)
  20. })
  21. }