grafana/pkg/infra/httpclient/httpclientprovider/user_agent_middleware.go
Marcus Efraimsson 348e76fc8e
Datasource: Shared HTTP client provider for core backend data sources and any data source using the data source proxy (#33439)
Uses new httpclient package from grafana-plugin-sdk-go introduced 
via grafana/grafana-plugin-sdk-go#328. 
Replaces the GetHTTPClient, GetTransport, GetTLSConfig methods defined 
on DataSource model.
Longer-term the goal is to migrate core HTTP backend data sources to use the 
SDK contracts and using httpclient.Provider for creating HTTP clients and such.

Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>
2021-05-19 23:53:41 +02:00

28 lines
902 B
Go

package httpclientprovider
import (
"net/http"
"github.com/grafana/grafana-plugin-sdk-go/backend/httpclient"
)
// SetUserAgentMiddlewareName is the middleware name used by SetUserAgentMiddleware.
const SetUserAgentMiddlewareName = "user-agent"
// SetUserAgentMiddleware is middleware that sets the HTTP header User-Agent on the outgoing request.
// If User-Agent already set, it will not be overridden by this middleware.
func SetUserAgentMiddleware(userAgent string) httpclient.Middleware {
return httpclient.NamedMiddlewareFunc(SetUserAgentMiddlewareName, func(opts httpclient.Options, next http.RoundTripper) http.RoundTripper {
if userAgent == "" {
return next
}
return httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
if req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", userAgent)
}
return next.RoundTrip(req)
})
})
}