Merge "Fetch of authorization token"
[nonrtric.git] / auth-token-fetch / HTTPClient.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2022: Nordix Foundation
6 //   %%
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
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
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===================================
19 //
20
21 package main
22
23 import (
24         "bytes"
25         "crypto/tls"
26         "fmt"
27         "io"
28
29         "net/http"
30         "net/url"
31         "time"
32 )
33
34 // HTTPClient interface
35 type HTTPClient interface {
36         Get(url string) (*http.Response, error)
37
38         Do(*http.Request) (*http.Response, error)
39 }
40
41 func CreateHttpClient(cert tls.Certificate, timeout time.Duration) *http.Client {
42         return &http.Client{
43                 Timeout:   timeout,
44                 Transport: createTransport(cert),
45         }
46 }
47
48 type RequestError struct {
49         StatusCode int
50         Body       []byte
51 }
52
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))
55 }
56
57 func Post(url string, body []byte, contentType string, client HTTPClient) error {
58         return do(http.MethodPost, url, body, contentType, client)
59 }
60
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) {
66                                 return nil
67                         } else {
68                                 return getRequestError(response)
69                         }
70                 } else {
71                         return respErr
72                 }
73         } else {
74                 return reqErr
75         }
76 }
77
78 func isResponseSuccess(statusCode int) bool {
79         return statusCode >= http.StatusOK && statusCode <= 299
80 }
81
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,
87                 Body:       responseData,
88         }
89         return putError
90 }
91
92 func createTransport(cert tls.Certificate) *http.Transport {
93         return &http.Transport{
94                 TLSClientConfig: &tls.Config{
95                         Certificates: []tls.Certificate{
96                                 cert,
97                         },
98                         InsecureSkipVerify: true,
99                 },
100         }
101 }
102
103 func IsUrlSecure(configUrl string) bool {
104         u, _ := url.Parse(configUrl)
105         return u.Scheme == "https"
106 }