To support SSL mode in CLI
[ealt-edge.git] / ocd / cli / ealt / cmd / adapter / httputil.go
1 /*
2 Copyright 2020 Huawei Technologies Co., Ltd.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package adapter
18
19 import (
20         "crypto/tls"
21         "crypto/x509"
22         "io/ioutil"
23         "log"
24         "net/http"
25         "os"
26 )
27
28 var rootKeyFile = os.Getenv("CertificateKeyFile")
29 var mode = os.Getenv("EALTSSLMode")
30
31 func GetHttpClient() http.Client {
32         if mode == "1" {
33                 client := getHttpsClient()
34                 return client
35         }
36         return http.Client{}
37 }
38
39 func getHttpsClient() http.Client {
40
41         caCert, err := ioutil.ReadFile(rootKeyFile)
42         if err != nil {
43                 log.Fatal(err)
44         }
45         caCertPool := x509.NewCertPool()
46         caCertPool.AppendCertsFromPEM(caCert)
47
48         client := &http.Client{
49                 Transport: &http.Transport{
50                         TLSClientConfig: &tls.Config{
51                                 RootCAs: caCertPool,
52                         },
53                 },
54         }
55         return *client
56 }