Skip to content

Commit e4c4e0b

Browse files
committed
example to implement custom logging and re-auth limits
1 parent 9368c00 commit e4c4e0b

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

‎FAQ.md‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Tips
2+
3+
## Implementing default logging and re-authentication attempts
4+
5+
You can implement custom logging and/or limit re-auth attempts by creating a custom HTTP client
6+
like the following and setting it as the provider client's HTTP Client (via the
7+
`gophercloud.ProviderClient.HTTPClient` field):
8+
9+
```go
10+
//...
11+
12+
// LogRoundTripper satisfies the http.RoundTripper interface and is used to
13+
// customize the default Gophercloud RoundTripper to allow for logging.
14+
type LogRoundTripper struct {
15+
rt http.RoundTripper
16+
numReauthAttempts int
17+
}
18+
19+
// newHTTPClient return a custom HTTP client that allows for logging relevant
20+
// information before and after the HTTP request.
21+
func newHTTPClient() http.Client {
22+
return http.Client{
23+
Transport: &LogRoundTripper{
24+
rt: http.DefaultTransport,
25+
},
26+
}
27+
}
28+
29+
// RoundTrip performs a round-trip HTTP request and logs relevant information about it.
30+
func (lrt *LogRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
31+
glog.Infof("Request URL: %s\n", request.URL)
32+
33+
response, err := lrt.rt.RoundTrip(request)
34+
if response == nil {
35+
return nil, err
36+
}
37+
38+
if response.StatusCode == http.StatusUnauthorized {
39+
if lrt.numReauthAttempts == 3 {
40+
return response, fmt.Errorf("Tried to re-authenticate 3 times with no success.")
41+
}
42+
lrt.numReauthAttempts++
43+
}
44+
45+
glog.Debugf("Response Status: %s\n", response.Status)
46+
47+
return response, nil
48+
}
49+
50+
endpoint := "https://127.0.0.1/auth"
51+
pc := openstack.NewClient(endpoint)
52+
pc.HTTPClient = newHTTPClient()
53+
54+
//...
55+
```

0 commit comments

Comments
 (0)