From 40e54a75a604a3d15ce928f1a21c2a47bfee0d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Dohn=C3=A1lek?= Date: Thu, 7 Apr 2022 09:13:14 +0200 Subject: [PATCH] Refactor apiClientImpl.DoGetFallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make apiClientImpl.DoGetFallback more idiomatic and efficient: * Save result of args.Encode() operation as it might be used 2 times in the function and due to looping and sorting it might be heavy. * Follow line-of-sight practise and therefore simplify the code. Signed-off-by: Tomáš Dohnálek --- api/prometheus/v1/api.go | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/api/prometheus/v1/api.go b/api/prometheus/v1/api.go index 857512fb8..0be68fad1 100644 --- a/api/prometheus/v1/api.go +++ b/api/prometheus/v1/api.go @@ -1133,7 +1133,8 @@ func (h *apiClientImpl) Do(ctx context.Context, req *http.Request) (*http.Respon // DoGetFallback will attempt to do the request as-is, and on a 405 or 501 it // will fallback to a GET request. func (h *apiClientImpl) DoGetFallback(ctx context.Context, u *url.URL, args url.Values) (*http.Response, []byte, Warnings, error) { - req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(args.Encode())) + encodedArgs := args.Encode() + req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(encodedArgs)) if err != nil { return nil, nil, nil, err } @@ -1141,19 +1142,14 @@ func (h *apiClientImpl) DoGetFallback(ctx context.Context, u *url.URL, args url. resp, body, warnings, err := h.Do(ctx, req) if resp != nil && (resp.StatusCode == http.StatusMethodNotAllowed || resp.StatusCode == http.StatusNotImplemented) { - u.RawQuery = args.Encode() + u.RawQuery = encodedArgs req, err = http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { return nil, nil, warnings, err } - - } else { - if err != nil { - return resp, body, warnings, err - } - return resp, body, warnings, nil + return h.Do(ctx, req) } - return h.Do(ctx, req) + return resp, body, warnings, err } func formatTime(t time.Time) string {