go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/cli/config/proxy.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package config
     5  
     6  import (
     7  	"net/http"
     8  	"net/url"
     9  	"os"
    10  
    11  	"github.com/spf13/viper"
    12  	"go.mondoo.com/ranger-rpc"
    13  )
    14  
    15  // GetAPIProxy returns the proxy URL from the environment variable MONDOO_API_PROXY and cli flag --api-proxy.
    16  // It should only be used when the options are not yet parsed, see CommonCliConfig.GetAPIProxy().
    17  func GetAPIProxy() (*url.URL, error) {
    18  	proxy, envSet := os.LookupEnv("MONDOO_API_PROXY")
    19  	if envSet {
    20  		return url.Parse(proxy)
    21  	}
    22  
    23  	proxy = viper.GetString("api_proxy")
    24  	if proxy != "" {
    25  		return url.Parse(proxy)
    26  	}
    27  
    28  	return nil, nil
    29  }
    30  
    31  func (c *CommonOpts) GetAPIProxy() (*url.URL, error) {
    32  	proxy, err := GetAPIProxy()
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	if proxy != nil {
    37  		return proxy, nil
    38  	}
    39  
    40  	// fallback to proxy from config file
    41  	if c.APIProxy != "" {
    42  		return url.Parse(c.APIProxy)
    43  	}
    44  
    45  	return nil, nil
    46  }
    47  
    48  func (c *CommonOpts) GetHttpClient() (*http.Client, error) {
    49  	proxy, err := c.GetAPIProxy()
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  	if proxy == nil {
    54  		return ranger.DefaultHttpClient(), nil
    55  	}
    56  	return ranger.NewHttpClient(ranger.WithProxy(proxy)), nil
    57  }