GoVultr

repository·master·Indexed 42 days ago

https://github.com/vultr/govultr

The official Go client for the Vultr V2 API. It allows developers to programmatically manage Vultr resources, including VPS instances, Bare Metal servers, backups, billing, and networking. The client provides services such as AccountService for bandwidth and account details, BareMetalServerService for lifecycle and power management, and BillingService for invoice and history retrieval.

Tokens
56.3K
Snippets
147
Records
198
Agent score
53%

What's inside GoVultr

  1. Handle pagination in list calls

    master

    All list calls in GoVultr v2 return a Meta struct containing pagination information. To navigate through large result sets, use the Links provided in the Meta object.

    Pagination Details

    • Meta.Total: The total number of items in the list.
    • Meta.Links.Next: The cursor string to use for the next page.
    • Meta.Links.Prev: The cursor string for the previous page.
    • ListOptions.PerPage: Controls the number of items per call. The default is 100, and the maximum is 500.

    To iterate through all pages, update the Cursor field in your ListOptions with the value from meta.Links.Next until it is empty.

    listOptions := &govultr.ListOptions{PerPage: 1}
    for {
        i, meta, err := client.Instance.List(ctx, listOptions)
        if err != nil {
            return nil, err
        }
        for _, v := range i {
            fmt.Println(v)
        }
    
        if meta.Links.Next == "" {
            break
        } else {
            listOptions.Cursor = meta.Links.Next
            continue
        }
    }
  2. Initialize a GoVultr client

    master

    To interact with the Vultr V2 API, you must instantiate a client using govultr.NewClient().

    Most operations require authentication via a Personal Access Token (PAT). You should use the golang.org/x/oauth2 library to create an *http.Client that includes your PAT in the Authorization header as a bearer api-key.

    If you pass nil to NewClient(), the client will only be able to access public routes (e.g., listing plans or applications) that do not require authentication.

    package main
    
    import (
      "context"
      "os"
    
      "github.com/vultr/govultr/v3"
      "golang.org/x/oauth2"
    )
    
    func main() {
      apiKey := os.Getenv("VultrAPIKey")
    
      config := &oauth2.Config{}
      ctx := context.Background()
      ts := config.TokenSource(ctx, &oauth2.Token{AccessToken: apiKey})
      vultrClient := govultr.NewClient(oauth2.NewClient(ctx, ts))
    }
  3. Define Organization Policy Documents

    master

    Organization policies are defined using an OrganizationPolicyDocument which contains a version and a slice of OrganizationPolicyStatement objects.

    Each OrganizationPolicyStatement includes:

    • Effect: Usually "Allow" or "Deny".
    • Action: A list of allowed or denied actions (e.g., ["compute:create"]).
    • Resource: A list of resources the action applies to.

    Note on Unmarshaling: The UnmarshalJSON method for OrganizationPolicyStatement is customized to handle cases where Action or Resource are provided as a single string instead of a JSON array, automatically converting them into slices for consistent use in Go.

    policyReq := &govultr.OrganizationPolicyReq{
        Name:        "ReadOnlyPolicy",
        Description: "Allows read-only access",
        PolicyDocument: govultr.OrganizationPolicyDocument{
            Version: "2012-10-17",
            Statement: []govultr.OrganizationPolicyStatement{
                {
                    Effect:   "Allow",
                    Action:   []string{"compute:get"},
                    Resource: []string{"arn:vultr:compute:*:*:instance/*"},
                },
            },
        },
    }
  4. Understand pagination with Meta and Links

    master

    The govultr package uses the Meta and Links types to provide pagination information for API responses.

    • Meta contains the Total number of items available and a pointer to a Links object.
    • Links provides the URLs for the Next and Prev pages, which can be used to navigate through paginated result sets using cursors.
    // Example structure of a paginated response metadata
    meta := govultr.Meta{
    	Total: 100,
    	Links: &govultr.Links{
    		Next: "https://api.vultr.com/v2/instances?cursor=abc",
    		Prev: "",
    	},
    }
  5. Manage instance power states and lifecycle

    master

    The InstanceService provides several methods for controlling the power state and lifecycle of an instance:

    • Start(ctx, id): Starts a running instance (restarts it).
    • Halt(ctx, id): Pauses an instance.
    • Reboot(ctx, id): Reboots an instance.
    • Reinstall(ctx, id, req): Reinstalls the instance, optionally changing the hostname via ReinstallReq.
    • MassStart(ctx, ids), MassHalt(ctx, ids), MassReboot(ctx, ids): Perform power operations on a list of instance IDs simultaneously.
    • Delete(ctx, id): Permanently deletes the instance and releases the IP address.
  6. VKE Data Models: Cluster, NodePool, and Node

    master

    The following types represent the core entities in the VKE API:

    • Cluster: Represents a full VKE cluster. Includes ID, Endpoint, Version, Status, and a slice of NodePools.
    • NodePool: A group of nodes. Includes Plan, NodeQuantity, MinNodes, MaxNodes, AutoScaler, and Taints.
    • Node: An individual worker node. Includes ID, Label, IP, and Status.
    • KubeConfig: Contains the KubeConfig string (base64 encoded) required to connect to the cluster.
  7. Create a Vultr Instance

    master

    To create a new VPS instance, use the Instance.Create method with an InstanceCreateReq object. You must specify parameters such as Label, Hostname, OsID, Plan, and Region.

    instanceOptions := &govultr.InstanceCreateReq{
      Label:                "awesome-go-app",
      Hostname:             "awesome-go.com",
      Backups:              "enabled",
      EnableIPv6:           BoolToBoolPtr(false),
      OsID:                 362,
      Plan:                 "vc2-1c-2gb",
      Region:               "ewr",
    }
    
    res, err := vultrClient.Instance.Create(context.Background(), instanceOptions)
    
    if err != nil {
      fmt.Println(err)
    }
  8. Configure client options

    master

    The GoVultr client provides three optional methods to customize behavior:

    • SetBaseURL(url string): Change the default Vultr base URL.
    • SetUserAgent(userAgent string): Change the default UserAgent string.
    • SetRateLimit(delay int): Set a delay (in milliseconds) between calls to avoid Vultr rate-limit errors.
    // Optional changes
    _ = vultrClient.SetBaseURL("https://api.vultr.com")
    vultrClient.SetUserAgent("mycool-app")
    vultrClient.SetRateLimit(500)
  9. Register a request completion callback

    master

    You can use OnRequestCompleted(rc RequestCompletionCallback) to register a function that is called after every successful request made to the Vultr API. This is useful for logging, telemetry, or debugging.

    RequestCompletionCallback signature: func(*http.Request, *http.Response)

    client.OnRequestCompleted(func(req *http.Request, resp *http.Response) {
        fmt.Printf("Request to %s completed with status %d\n", req.URL, resp.StatusCode)
    })
  10. List users with pagination and options

    master

    To retrieve a list of users, use the List method. It accepts *ListOptions which are used to construct query parameters for the request (such as pagination or filtering). It returns a slice of User objects, a *Meta object containing pagination metadata, and the *http.Response.

    users, meta, resp, err := userService.List(ctx, &govultr.ListOptions{
        // Add ListOptions fields here
    })
  11. Manage Managed Databases with DatabaseService

    master

    The DatabaseService interface provides a comprehensive set of methods to manage Vultr Managed Databases. It allows for lifecycle management (Create, Get, Update, Delete), user management, logical database management, and specialized operations for different engines like Kafka (topics, quotas, connectors) and PostgreSQL (connection pools).

    type DatabaseService interface {
    	ListPlans(ctx context.Context, options *DBPlanListOptions) ([]DatabasePlan, *Meta, *http.Response, error)
    	List(ctx context.Context, options *DBListOptions) ([]Database, *Meta, *http.Response, error)
    	Create(ctx context.Context, databaseReq *DatabaseCreateReq) (*Database, *http.Response, error)
    	Get(ctx context.Context, databaseID string) (*Database, *http.Response, error)
    	Update(ctx context.Context, databaseID string, databaseReq *DatabaseUpdateReq) (*Database, *http.Response, error)
    	Delete(ctx context.Context, databaseID string) error
    	// ... other methods
    }