Skip to content

Commit

Permalink
set user agent on scrape requests to nginx
Browse files Browse the repository at this point in the history
  • Loading branch information
asherf authored and pleshakov committed Nov 13, 2019
1 parent 319a7fd commit 73a7537
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,15 @@ func main() {
scrapeURI = &newScrapeURI
}

userAgent := fmt.Sprintf("NGINX-Prometheus-Exporter/v%v", version)
userAgentRT := &userAgentRoundTripper{
agent: userAgent,
rt: transport,
}

httpClient := &http.Client{
Timeout: timeout.Duration,
Transport: transport,
Transport: userAgentRT,
}

srv := http.Server{}
Expand Down Expand Up @@ -290,3 +296,28 @@ func main() {
log.Printf("NGINX Prometheus Exporter has successfully started")
log.Fatal(srv.Serve(listener))
}

type userAgentRoundTripper struct {
agent string
rt http.RoundTripper
}

func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req = cloneRequest(req)
req.Header.Set("User-Agent", rt.agent)
return rt.rt.RoundTrip(req)
}

func cloneRequest(req *http.Request) *http.Request {
r := new(http.Request)
*r = *req // shallow clone

// deep copy headers
r.Header = make(http.Header, len(req.Header))
for key, values := range req.Header {
newValues := make([]string, len(values))
copy(newValues, values)
r.Header[key] = newValues
}
return r
}

0 comments on commit 73a7537

Please sign in to comment.