gunziphandler.go 576 B

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