|
| 1 | +package clients |
| 2 | + |
| 3 | +import ( |
| 4 | + "code.cloudfoundry.org/cli/api/cloudcontroller" |
| 5 | + "code.cloudfoundry.org/cli/api/cloudcontroller/ccv3" |
| 6 | + "crypto/tls" |
| 7 | + "io" |
| 8 | + "net" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +type rawConnection struct { |
| 15 | + httpClient *http.Client |
| 16 | +} |
| 17 | + |
| 18 | +func (c rawConnection) Make(request *cloudcontroller.Request, passedResponse *cloudcontroller.Response) error { |
| 19 | + response, err := c.httpClient.Do(request.Request) |
| 20 | + if err != nil { |
| 21 | + return err |
| 22 | + } |
| 23 | + passedResponse.HTTPResponse = response |
| 24 | + return nil |
| 25 | +} |
| 26 | + |
| 27 | +// RawClientConfig - configuration for RawClient |
| 28 | +type RawClientConfig struct { |
| 29 | + DialTimeout time.Duration |
| 30 | + SkipSSLValidation bool |
| 31 | + ApiEndpoint string |
| 32 | +} |
| 33 | + |
| 34 | +// Raw http client has uaa client authentication to make raw request with golang native api. |
| 35 | +type RawClient struct { |
| 36 | + connection cloudcontroller.Connection |
| 37 | + apiEndpoint string |
| 38 | + wrappers []ccv3.ConnectionWrapper |
| 39 | +} |
| 40 | + |
| 41 | +// NewRawClient - |
| 42 | +func NewRawClient(config RawClientConfig, wrappers ...ccv3.ConnectionWrapper) *RawClient { |
| 43 | + httpClient := &http.Client{ |
| 44 | + Transport: &http.Transport{ |
| 45 | + TLSClientConfig: &tls.Config{ |
| 46 | + InsecureSkipVerify: config.SkipSSLValidation, |
| 47 | + }, |
| 48 | + Proxy: http.ProxyFromEnvironment, |
| 49 | + DialContext: (&net.Dialer{ |
| 50 | + KeepAlive: 30 * time.Second, |
| 51 | + Timeout: config.DialTimeout, |
| 52 | + }).DialContext, |
| 53 | + }, |
| 54 | + } |
| 55 | + var connection cloudcontroller.Connection = &rawConnection{httpClient} |
| 56 | + for _, wrapper := range wrappers { |
| 57 | + connection = wrapper.Wrap(connection) |
| 58 | + } |
| 59 | + return &RawClient{ |
| 60 | + connection: connection, |
| 61 | + apiEndpoint: strings.TrimSuffix(config.ApiEndpoint, "/"), |
| 62 | + wrappers: wrappers, |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// Do - Do the request with given http client and wrappers |
| 67 | +func (c RawClient) Do(req *http.Request) (*http.Response, error) { |
| 68 | + resp := &cloudcontroller.Response{} |
| 69 | + err := c.connection.Make(&cloudcontroller.Request{ |
| 70 | + Request: req, |
| 71 | + }, resp) |
| 72 | + return resp.HTTPResponse, err |
| 73 | +} |
| 74 | + |
| 75 | +// NewRequest - Create a new request with setting api endpoint to the path |
| 76 | +func (c RawClient) NewRequest(method, path string, body io.ReadCloser) (*http.Request, error) { |
| 77 | + return http.NewRequest(method, c.apiEndpoint+path, body) |
| 78 | +} |
0 commit comments