Skip to content

Commit 73a7537

Browse files
asherfpleshakov
authored andcommitted
set user agent on scrape requests to nginx
1 parent 319a7fd commit 73a7537

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

exporter.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,15 @@ func main() {
233233
scrapeURI = &newScrapeURI
234234
}
235235

236+
userAgent := fmt.Sprintf("NGINX-Prometheus-Exporter/v%v", version)
237+
userAgentRT := &userAgentRoundTripper{
238+
agent: userAgent,
239+
rt: transport,
240+
}
241+
236242
httpClient := &http.Client{
237243
Timeout: timeout.Duration,
238-
Transport: transport,
244+
Transport: userAgentRT,
239245
}
240246

241247
srv := http.Server{}
@@ -290,3 +296,28 @@ func main() {
290296
log.Printf("NGINX Prometheus Exporter has successfully started")
291297
log.Fatal(srv.Serve(listener))
292298
}
299+
300+
type userAgentRoundTripper struct {
301+
agent string
302+
rt http.RoundTripper
303+
}
304+
305+
func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
306+
req = cloneRequest(req)
307+
req.Header.Set("User-Agent", rt.agent)
308+
return rt.rt.RoundTrip(req)
309+
}
310+
311+
func cloneRequest(req *http.Request) *http.Request {
312+
r := new(http.Request)
313+
*r = *req // shallow clone
314+
315+
// deep copy headers
316+
r.Header = make(http.Header, len(req.Header))
317+
for key, values := range req.Header {
318+
newValues := make([]string, len(values))
319+
copy(newValues, values)
320+
r.Header[key] = newValues
321+
}
322+
return r
323+
}

0 commit comments

Comments
 (0)