regions.go raw
1 package govultr
2
3 import (
4 "context"
5 "fmt"
6 "net/http"
7
8 "github.com/google/go-querystring/query"
9 )
10
11 // RegionService is the interface to interact with Region endpoints on the Vultr API
12 // Link : https://www.vultr.com/api/#tag/region
13 type RegionService interface {
14 Availability(ctx context.Context, regionID string, planType string) (*PlanAvailability, *http.Response, error)
15 List(ctx context.Context, options *ListOptions) ([]Region, *Meta, *http.Response, error)
16 }
17
18 var _ RegionService = &RegionServiceHandler{}
19
20 // RegionServiceHandler handles interaction with the region methods for the Vultr API
21 type RegionServiceHandler struct {
22 client *Client
23 }
24
25 // Region represents a Vultr region
26 type Region struct {
27 ID string `json:"id"`
28 City string `json:"city"`
29 Country string `json:"country"`
30 Continent string `json:"continent,omitempty"`
31 Options []string `json:"options"`
32 }
33
34 type regionBase struct {
35 Regions []Region `json:"regions"`
36 Meta *Meta
37 }
38
39 // PlanAvailability contains all available plans.
40 type PlanAvailability struct {
41 AvailablePlans []string `json:"available_plans"`
42 }
43
44 // List returns all available regions
45 func (r *RegionServiceHandler) List(ctx context.Context, options *ListOptions) ([]Region, *Meta, *http.Response, error) {
46 uri := "/v2/regions"
47
48 req, err := r.client.NewRequest(ctx, http.MethodGet, uri, nil)
49 if err != nil {
50 return nil, nil, nil, err
51 }
52
53 newValues, err := query.Values(options)
54 if err != nil {
55 return nil, nil, nil, err
56 }
57
58 req.URL.RawQuery = newValues.Encode()
59
60 regions := new(regionBase)
61 resp, err := r.client.DoWithContext(ctx, req, ®ions)
62 if err != nil {
63 return nil, nil, resp, err
64 }
65
66 return regions.Regions, regions.Meta, resp, nil
67 }
68
69 // Availability retrieves a list of the plan IDs currently available for a given location.
70 func (r *RegionServiceHandler) Availability(ctx context.Context, regionID, planType string) (*PlanAvailability, *http.Response, error) {
71 uri := fmt.Sprintf("/v2/regions/%s/availability", regionID)
72
73 req, err := r.client.NewRequest(ctx, http.MethodGet, uri, nil)
74
75 if err != nil {
76 return nil, nil, err
77 }
78
79 // Optional planType filter
80 if planType != "" {
81 q := req.URL.Query()
82 q.Add("type", planType)
83 req.URL.RawQuery = q.Encode()
84 }
85
86 plans := new(PlanAvailability)
87 resp, err := r.client.DoWithContext(ctx, req, plans)
88 if err != nil {
89 return nil, resp, err
90 }
91
92 return plans, resp, nil
93 }
94