grafana/pkg/infra/httpclient/httpclientprovider/response_limit_middleware.go
Marcus Efraimsson 3be452f995
DataProxy: Fix issue overriding response body when response status is 101 (#41364)
When a request going through Grafana data source proxy responds with a websocket 
upgrade response we cannot override the response body since it produces an error. 
This problem seems to have been introduced in Grafana v8.0 by #38962. 
In addition #40303 added same problem.

Fixes #41292
2021-11-09 14:33:54 +01:00

32 lines
910 B
Go

package httpclientprovider
import (
"net/http"
sdkhttpclient "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
"github.com/grafana/grafana/pkg/infra/httpclient"
)
// ResponseLimitMiddlewareName is the middleware name used by ResponseLimitMiddleware.
const ResponseLimitMiddlewareName = "response-limit"
func ResponseLimitMiddleware(limit int64) sdkhttpclient.Middleware {
return sdkhttpclient.NamedMiddlewareFunc(ResponseLimitMiddlewareName, func(opts sdkhttpclient.Options, next http.RoundTripper) http.RoundTripper {
if limit <= 0 {
return next
}
return sdkhttpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
res, err := next.RoundTrip(req)
if err != nil {
return nil, err
}
if res != nil && res.StatusCode != http.StatusSwitchingProtocols {
res.Body = httpclient.MaxBytesReader(res.Body, limit)
}
return res, nil
})
})
}