|
| 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