2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: 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===================================
34 // HTTPClient interface
35 type HTTPClient interface {
36 Get(url string) (*http.Response, error)
38 Do(*http.Request) (*http.Response, error)
41 func CreateHttpClient(cert tls.Certificate, timeout time.Duration) *http.Client {
44 Transport: createTransport(cert),
48 type RequestError struct {
53 func (pe RequestError) Error() string {
54 return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
57 func Post(url string, body []byte, contentType string, client HTTPClient) error {
58 return do(http.MethodPost, url, body, contentType, client)
61 func do(method string, url string, body []byte, contentType string, client HTTPClient) error {
62 if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
63 req.Header.Set("Content-Type", contentType)
64 if response, respErr := client.Do(req); respErr == nil {
65 if isResponseSuccess(response.StatusCode) {
68 return getRequestError(response)
78 func isResponseSuccess(statusCode int) bool {
79 return statusCode >= http.StatusOK && statusCode <= 299
82 func getRequestError(response *http.Response) RequestError {
83 defer response.Body.Close()
84 responseData, _ := io.ReadAll(response.Body)
85 putError := RequestError{
86 StatusCode: response.StatusCode,
92 func createTransport(cert tls.Certificate) *http.Transport {
93 return &http.Transport{
94 TLSClientConfig: &tls.Config{
95 Certificates: []tls.Certificate{
98 InsecureSkipVerify: true,
103 func IsUrlSecure(configUrl string) bool {
104 u, _ := url.Parse(configUrl)
105 return u.Scheme == "https"