2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 // ========================LICENSE_END===================================
33 "github.com/hashicorp/go-retryablehttp"
34 log "github.com/sirupsen/logrus"
37 // HTTPClient interface
38 type HTTPClient interface {
39 Get(url string) (*http.Response, error)
41 Do(*http.Request) (*http.Response, error)
44 type RequestError struct {
49 func (pe RequestError) Error() string {
50 return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
53 func Get(url string, client HTTPClient) ([]byte, error) {
54 if response, err := client.Get(url); err == nil {
55 if isResponseSuccess(response.StatusCode) {
56 defer response.Body.Close()
57 if responseData, err := io.ReadAll(response.Body); err == nil {
58 return responseData, nil
63 return nil, getRequestError(response)
70 func Put(url string, body []byte, client HTTPClient) error {
71 return do(http.MethodPut, url, body, client)
74 func Post(url string, body []byte, client HTTPClient) error {
75 return do(http.MethodPost, url, body, client)
78 func do(method string, url string, body []byte, client HTTPClient) error {
79 if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
80 req.Header.Set("Content-Type", "application/json")
81 if response, respErr := client.Do(req); respErr == nil {
82 if isResponseSuccess(response.StatusCode) {
85 return getRequestError(response)
95 func isResponseSuccess(statusCode int) bool {
96 return statusCode >= http.StatusOK && statusCode <= 299
99 func getRequestError(response *http.Response) RequestError {
100 defer response.Body.Close()
101 responseData, _ := io.ReadAll(response.Body)
102 putError := RequestError{
103 StatusCode: response.StatusCode,
109 func CreateClientCertificate(certPath string, keyPath string) (tls.Certificate, error) {
110 if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
113 return tls.Certificate{}, fmt.Errorf("cannot create x509 keypair from cert file %s and key file %s due to: %v", certPath, keyPath, err)
117 func CreateRetryClient(cert tls.Certificate) *http.Client {
118 rawRetryClient := retryablehttp.NewClient()
119 rawRetryClient.Logger = leveledLogger{}
120 rawRetryClient.RetryWaitMax = time.Minute
121 rawRetryClient.RetryMax = math.MaxInt
122 rawRetryClient.HTTPClient.Transport = getSecureTransportWithoutVerify(cert)
124 client := rawRetryClient.StandardClient()
128 func CreateClientWithoutRetry(cert tls.Certificate, timeout time.Duration) *http.Client {
131 Transport: getSecureTransportWithoutVerify(cert),
135 func getSecureTransportWithoutVerify(cert tls.Certificate) *http.Transport {
136 return &http.Transport{
137 TLSClientConfig: &tls.Config{
138 Certificates: []tls.Certificate{
141 InsecureSkipVerify: true,
146 func IsUrlSecure(configUrl string) bool {
147 u, _ := url.Parse(configUrl)
148 return u.Scheme == "https"
151 // Used to get leveled logging in the RetryClient
152 type leveledLogger struct {
155 func (ll leveledLogger) Error(msg string, keysAndValues ...interface{}) {
156 log.WithFields(getFields(keysAndValues)).Error(msg)
158 func (ll leveledLogger) Info(msg string, keysAndValues ...interface{}) {
159 log.WithFields(getFields(keysAndValues)).Info(msg)
161 func (ll leveledLogger) Debug(msg string, keysAndValues ...interface{}) {
162 log.WithFields(getFields(keysAndValues)).Debug(msg)
164 func (ll leveledLogger) Warn(msg string, keysAndValues ...interface{}) {
165 log.WithFields(getFields(keysAndValues)).Warn(msg)
168 func getFields(keysAndValues []interface{}) log.Fields {
169 fields := log.Fields{}
170 for i := 0; i < len(keysAndValues); i = i + 2 {
171 fields[fmt.Sprint(keysAndValues[i])] = keysAndValues[i+1]