Skip to content

Commit 4efa483

Browse files
committed
feat: adding example of overwriting User-Agent header
1 parent 4a444de commit 4efa483

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

example_ua_set_test.go

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Copyright 2022 InfluxData, Inc. All rights reserved.
2+
// Use of this source code is governed by MIT
3+
// license that can be found in the LICENSE file.
4+
5+
package influxdb2_test
6+
7+
import (
8+
"context"
9+
"fmt"
10+
"net/http"
11+
12+
"github.com/influxdata/influxdb-client-go/v2"
13+
ihttp "github.com/influxdata/influxdb-client-go/v2/api/http"
14+
)
15+
16+
// UserAgentSetter is the implementation of Doer interface for setting User-Agent header
17+
type UserAgentSetter struct {
18+
UserAgent string
19+
RequestDoer ihttp.Doer
20+
}
21+
22+
// Do fulfills the Doer interface
23+
func (u *UserAgentSetter) Do(req *http.Request) (*http.Response, error) {
24+
// Set User-Agent header to request
25+
req.Header.Set("User-Agent", u.UserAgent)
26+
// Call original Doer to proceed with request
27+
return u.RequestDoer.Do(req)
28+
}
29+
30+
func ExampleClient_customUserAgentHeader() {
31+
// Set custom Doer to HTTPOptions
32+
opts := influxdb2.DefaultOptions()
33+
opts.HTTPOptions().SetHTTPDoer(&UserAgentSetter{
34+
UserAgent: "NetMonitor/1.1",
35+
RequestDoer: http.DefaultClient,
36+
})
37+
38+
//Create client with customized options
39+
client := influxdb2.NewClientWithOptions("http://localhost:8086", "my-token", opts)
40+
41+
// Always close client at the end
42+
defer client.Close()
43+
44+
// Issue a call with custom User-Agent header
45+
resp, err := client.Ping(context.Background())
46+
if err != nil {
47+
panic(err)
48+
}
49+
if resp {
50+
fmt.Println("Server is up")
51+
} else {
52+
fmt.Println("Server is down")
53+
}
54+
}

0 commit comments

Comments
 (0)