2022-01-04 08:22:33 -06:00
|
|
|
package middleware
|
2021-05-27 05:43:21 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
|
|
|
|
sdkhttpclient "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
|
2023-01-30 02:38:51 -06:00
|
|
|
|
2023-10-20 08:54:27 -05:00
|
|
|
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
|
2021-05-27 05:43:21 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
customQueryParametersMiddlewareName = "prom-custom-query-parameters"
|
|
|
|
customQueryParametersKey = "customQueryParameters"
|
2021-12-03 09:28:05 -06:00
|
|
|
grafanaDataKey = "grafanaData"
|
2021-05-27 05:43:21 -05:00
|
|
|
)
|
|
|
|
|
2022-01-04 08:22:33 -06:00
|
|
|
func CustomQueryParameters(logger log.Logger) sdkhttpclient.Middleware {
|
2021-05-27 05:43:21 -05:00
|
|
|
return sdkhttpclient.NamedMiddlewareFunc(customQueryParametersMiddlewareName, func(opts sdkhttpclient.Options, next http.RoundTripper) http.RoundTripper {
|
2021-12-03 09:28:05 -06:00
|
|
|
grafanaData, exists := opts.CustomOptions[grafanaDataKey]
|
2021-05-27 05:43:21 -05:00
|
|
|
if !exists {
|
|
|
|
return next
|
|
|
|
}
|
2021-12-03 09:28:05 -06:00
|
|
|
|
2023-08-30 10:46:47 -05:00
|
|
|
data, ok := grafanaData.(map[string]any)
|
2021-12-03 09:28:05 -06:00
|
|
|
if !ok {
|
|
|
|
return next
|
|
|
|
}
|
|
|
|
customQueryParamsVal, exists := data[customQueryParametersKey]
|
|
|
|
if !exists {
|
|
|
|
return next
|
|
|
|
}
|
|
|
|
|
2021-05-27 05:43:21 -05:00
|
|
|
customQueryParams, ok := customQueryParamsVal.(string)
|
|
|
|
if !ok || customQueryParams == "" {
|
|
|
|
return next
|
|
|
|
}
|
|
|
|
|
2021-06-01 07:59:44 -05:00
|
|
|
values, err := url.ParseQuery(customQueryParams)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("Failed to parse custom query parameters, skipping middleware", "error", err)
|
|
|
|
return next
|
|
|
|
}
|
|
|
|
|
2021-05-27 05:43:21 -05:00
|
|
|
return sdkhttpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
2021-06-01 07:59:44 -05:00
|
|
|
q := req.URL.Query()
|
|
|
|
for k, keyValues := range values {
|
|
|
|
for _, value := range keyValues {
|
|
|
|
q.Add(k, value)
|
2021-05-27 05:43:21 -05:00
|
|
|
}
|
|
|
|
}
|
2021-06-01 07:59:44 -05:00
|
|
|
req.URL.RawQuery = q.Encode()
|
2021-05-27 05:43:21 -05:00
|
|
|
|
|
|
|
return next.RoundTrip(req)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|