github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/cloud/iks/regions.go (about)

     1  package iks
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	gohttp "net/http"
     8  
     9  	ibmcloud "github.com/IBM-Cloud/bluemix-go"
    10  	"github.com/IBM-Cloud/bluemix-go/client"
    11  	"github.com/IBM-Cloud/bluemix-go/http"
    12  	"github.com/IBM-Cloud/bluemix-go/rest"
    13  )
    14  
    15  const containerEndpointOfPublicBluemix = "https://containers.bluemix.net"
    16  
    17  type Region struct {
    18  	Name        string `json:"name"`
    19  	Alias       string `json:"alias"`
    20  	CfURL       string `json:"cfURL"`
    21  	FreeEnabled bool   `json:"freeEnabled"`
    22  }
    23  type RegionResponse struct {
    24  	Regions []Region `json:"regions"`
    25  }
    26  
    27  type Regions interface {
    28  	GetRegions() ([]Region, error)
    29  	GetRegion(region string) (*Region, error)
    30  }
    31  
    32  type region struct {
    33  	*client.Client
    34  	regions []Region
    35  }
    36  
    37  func newRegionsAPI(c *client.Client) Regions {
    38  	return &region{
    39  		Client:  c,
    40  		regions: nil,
    41  	}
    42  }
    43  
    44  func (v *region) fetch() error {
    45  	if v.regions == nil {
    46  		regions := RegionResponse{}
    47  		_, err := v.Client.Get("/v1/regions", &regions)
    48  		if err != nil {
    49  			return err
    50  		}
    51  		v.regions = regions.Regions
    52  	}
    53  	return nil
    54  }
    55  
    56  //List ...
    57  func (v *region) GetRegions() ([]Region, error) {
    58  	if err := v.fetch(); err != nil {
    59  		return nil, err
    60  	}
    61  	return v.regions, nil
    62  }
    63  func (v *region) GetRegion(regionarg string) (*Region, error) {
    64  	if err := v.fetch(); err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	for _, region := range v.regions {
    69  		if strings.Compare(regionarg, region.Name) == 0 {
    70  			return &region, nil
    71  		}
    72  	}
    73  	return nil, fmt.Errorf("region %q not found", regionarg)
    74  }
    75  
    76  func GetAuthRegions(config *ibmcloud.Config) ([]string, error) {
    77  
    78  	regions := RegionResponse{}
    79  	if config.HTTPClient == nil {
    80  		config.HTTPClient = http.NewHTTPClient(config)
    81  	}
    82  	client := client.New(config, ibmcloud.MccpService, nil)
    83  	resp, err := client.SendRequest(rest.GetRequest(containerEndpointOfPublicBluemix+"/v1/regions"), &regions)
    84  
    85  	if resp.StatusCode == gohttp.StatusNotFound {
    86  		return []string{}, nil
    87  	}
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  
    92  	strregions := make([]string, len(regions.Regions))
    93  
    94  	for i, region := range regions.Regions {
    95  		strregions[i] = region.Alias
    96  	}
    97  
    98  	return strregions, nil
    99  }