subaccount.go raw
1 package govultr
2
3 import (
4 "context"
5 "net/http"
6 )
7
8 // SubAccountService is the interface to interact with sub-accounts endpoint on the Vultr API
9 // Link : https://www.vultr.com/api/#tag/subaccount
10 type SubAccountService interface {
11 List(ctx context.Context, options *ListOptions) ([]SubAccount, *Meta, *http.Response, error)
12 Create(ctx context.Context, saReq *SubAccountReq) (*SubAccount, *http.Response, error)
13 }
14
15 // SubAccountServiceHandler handles interaction with the account methods for the Vultr API
16 type SubAccountServiceHandler struct {
17 client *Client
18 }
19
20 type subAccountsBase struct {
21 SubAccounts []SubAccount `json:"subaccounts"`
22 Meta *Meta `json:"meta"`
23 }
24
25 type subAccountBase struct {
26 SubAccount *SubAccount `json:"subaccount"`
27 }
28
29 // SubAccount represents a Vultr sub-account
30 type SubAccount struct {
31 ID string `json:"id"`
32 Email string `json:"email"`
33 Name string `json:"subaccount_name"`
34 OtherID string `json:"subaccount_id"`
35 Activated bool `json:"activated"`
36 Balance int `json:"balance"`
37 PendingCharges int `json:"pending_charges"`
38 }
39
40 // SubAccountReq is the sub-account struct for create calls
41 type SubAccountReq struct {
42 Email string `json:"email"`
43 Name string `json:"subaccount_name,omitempty"`
44 OtherID string `json:"subaccount_id,omitempty"`
45 }
46
47 // List all sub-accounts
48 func (s *SubAccountServiceHandler) List(ctx context.Context, options *ListOptions) ([]SubAccount, *Meta, *http.Response, error) {
49 uri := "/v2/subaccounts"
50 req, err := s.client.NewRequest(ctx, http.MethodGet, uri, nil)
51 if err != nil {
52 return nil, nil, nil, err
53 }
54
55 sas := new(subAccountsBase)
56 resp, err := s.client.DoWithContext(ctx, req, sas)
57 if err != nil {
58 return nil, nil, resp, err
59 }
60
61 return sas.SubAccounts, sas.Meta, resp, nil
62 }
63
64 // Create a sub-account
65 func (s *SubAccountServiceHandler) Create(ctx context.Context, saReq *SubAccountReq) (*SubAccount, *http.Response, error) {
66 uri := "/v2/subaccounts"
67 req, err := s.client.NewRequest(ctx, http.MethodPost, uri, saReq)
68 if err != nil {
69 return nil, nil, err
70 }
71
72 sa := new(subAccountBase)
73 resp, err := s.client.DoWithContext(ctx, req, sa)
74 if err != nil {
75 return nil, resp, err
76 }
77
78 return sa.SubAccount, resp, nil
79 }
80