go-zero/rest/handler/gunziphandler.go

29 lines
580 B
Go
Raw Normal View History

2020-07-29 18:00:04 +08:00
package handler
2020-07-26 17:09:05 +08:00
import (
"compress/gzip"
"net/http"
"strings"
"github.com/zeromicro/go-zero/rest/httpx"
2020-07-26 17:09:05 +08:00
)
const gzipEncoding = "gzip"
2021-03-01 19:15:35 +08:00
// GunzipHandler returns a middleware to gunzip http request body.
2020-07-26 17:09:05 +08:00
func GunzipHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get(httpx.ContentEncoding), gzipEncoding) {
reader, err := gzip.NewReader(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
r.Body = reader
}
next.ServeHTTP(w, r)
})
}