### Example: Get and Print Instance Upgrades Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Demonstrates how to retrieve available upgrade options for an instance and print the available plans. ```go upgrades, _, err := client.Instance.GetUpgrades(ctx, instanceID) fmt.Printf("Available plans: %v\n", upgrades.Plans) ``` -------------------------------- ### Install GoVultr Package Source: https://github.com/vultr/govultr/blob/master/README.md Use 'go get' to install or update the GoVultr package. ```sh go get -u github.com/vultr/govultr/v3 ``` -------------------------------- ### Full Vultr Workflow Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/quick-start.md A comprehensive example demonstrating a typical workflow: setting up the client, checking account details, creating a compute instance, waiting for it to become active, setting up a firewall group with a rule, and adding a DNS domain. ```go package main import ( "context" "fmt" "os" "time" "github.com/vultr/govultr/v3" "golang.org/x/oauth2" ) func main() { ctx := context.Background() apiKey := os.Getenv("VULTR_API_KEY") config := &oauth2.Config{} ts := config.TokenSource(ctx, &oauth2.Token{AccessToken: apiKey}) client := govultr.NewClient(oauth2.NewClient(ctx, ts)) client.SetRateLimit(500 * time.Millisecond) account, _, _ := client.Account.Get(ctx) fmt.Printf("Account: %s\n", account.Name) instance, _, err := client.Instance.Create(ctx, &govultr.InstanceCreateReq{ Region: "ewr", Plan: "vc2-1c-2gb", Label: "demo-instance", Hostname: "demo.example.com", OsID: 387, EnableIPv6: govultr.BoolToBoolPtr(true), }) if err != nil { panic(err) } fmt.Printf("Created instance: %s\n", instance.ID) for i := 0; i < 60; i++ { inst, _, _ := client.Instance.Get(ctx, instance.ID) if inst.Status == "active" { fmt.Printf("Instance is ready: %s\n", inst.MainIP) break } fmt.Printf("Status: %s, waiting...\n", inst.Status) time.Sleep(5 * time.Second) } fw, _, _ := client.FirewallGroup.Create(ctx, &govultr.FirewallGroupReq{ Description: "demo-firewall", }) client.FirewallRule.Create(ctx, fw.ID, &govultr.FirewallRuleReq{ IPType: "v4", Protocol: "tcp", Port: "22", Subnet: "0.0.0.0", SubnetSize: 0, }) domain, _, _ := client.Domain.Create(ctx, &govultr.DomainReq{ Domain: "example.com", IP: instance.MainIP, }) fmt.Printf("\nSetup complete:\n") fmt.Printf("- Instance: %s (%s)\n", instance.Label, instance.MainIP) fmt.Printf("- Firewall: %s\n", fw.Description) fmt.Printf("- Domain: %s\n", domain.Domain) } ``` -------------------------------- ### Backup and Restore Workflow Example Go Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md A comprehensive example demonstrating enabling automated backups, creating a manual snapshot, monitoring its status, listing snapshots, and preparing for a restore operation. ```go package main import ( "context" "fmt" "time" "github.com/vultr/govultr/v3" ) func main() { ctx := context.Background() client := govultr.NewClient(httpClient) instanceID := "my-instance-id" // Step 1: Enable automated backups schedule := &govultr.BackupScheduleReq{ Type: "daily", Hour: govultr.IntToIntPtr(3), // 3 AM UTC } client.Instance.SetBackupSchedule(ctx, instanceID, schedule) fmt.Println("Automated backups enabled (daily at 3 AM UTC)") // Step 2: Create manual snapshot before maintenance snapshot, _, _ := client.Snapshot.Create(ctx, &govultr.SnapshotReq{ InstanceID: instanceID, Description: fmt.Sprintf("pre-maintenance-%d", time.Now().Unix()), }) fmt.Printf("Manual snapshot created: %s\n", snapshot.ID) // Step 3: Wait for snapshot to complete for { snap, _, _ := client.Snapshot.Get(ctx, snapshot.ID) if snap.Status == "complete" { sizeGB := snap.Size / (1024 * 1024 * 1024) fmt.Printf("Snapshot complete: %d GB\n", sizeGB) break } fmt.Printf("Snapshot status: %s, waiting...\n", snap.Status) time.Sleep(10 * time.Second) } // Step 4: List all snapshots snapshots, meta, _, _ := client.Snapshot.List(ctx, nil) fmt.Printf("Total snapshots: %d\n", meta.Total) // Step 5: Restore from snapshot if needed // restore := &govultr.RestoreReq{ // SnapshotID: snapshot.ID, // } // client.Instance.Restore(ctx, instanceID, restore) } ``` -------------------------------- ### Start Instance Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Starts a stopped Vultr instance. ```APIDOC ## POST /v2/instances/{instanceID}/start ### Description Starts a stopped Vultr instance. ### Method POST ### Endpoint /v2/instances/{instanceID}/start ### Parameters #### Path Parameters - **instanceID** (string) - Required - The ID of the instance to start. ### Response #### Success Response (200) - **error** (error) - An error if the start operation failed. ``` -------------------------------- ### Get Specific Backup Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Shows how to retrieve details for a single backup using its ID. Includes basic error checking. ```go backup, _, err := client.Backup.Get(ctx, backupID) if err != nil { panic(err) } fmt.Printf("Backup: %s, Size: %d bytes\n", backup.ID, backup.Size) ``` -------------------------------- ### Create Firewall Rule Examples Source: https://github.com/vultr/govultr/blob/master/_autodocs/firewall-service.md Examples demonstrating how to create different types of firewall rules, such as SSH, HTTPS, internal traffic, and dropping specific IPs. Ensure you have a firewall group ID and a configured client. ```go sshRule := &govultr.FirewallRuleReq{ IPType: "v4", Protocol: "tcp", Port: "22", Subnet: "0.0.0.0", SubnetSize: 0, Notes: "SSH access", } rule, _, err := client.FirewallRule.Create(ctx, groupID, sshRule) ``` ```go httpsRule := &govultr.FirewallRuleReq{ IPType: "v4", Protocol: "tcp", Port: "443", Subnet: "203.0.113.0", SubnetSize: 24, Notes: "HTTPS from office", } client.FirewallRule.Create(ctx, groupID, httpsRule) ``` ```go allRule := &govultr.FirewallRuleReq{ IPType: "v4", Protocol: "tcp", Port: "1:65535", Subnet: "10.0.0.0", SubnetSize: 8, Notes: "Internal traffic", } client.FirewallRule.Create(ctx, groupID, allRule) ``` ```go dropRule := &govultr.FirewallRuleReq{ IPType: "v4", Protocol: "tcp", Port: "80", Subnet: "192.0.2.100", SubnetSize: 32, Notes: "Block malicious IP", } client.FirewallRule.Create(ctx, groupID, dropRule) ``` -------------------------------- ### Get VPC Go Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Retrieves details for a specific VPC using its ID. The VPC ID must be a valid UUID. ```go vpc, _, err := client.VPC.Get(ctx, vpcID) if err != nil { panic(err) } fmt.Printf("VPC %s: %s/%d in %s\n", vpc.ID, vpc.V4Subnet, vpc.V4SubnetMask, vpc.Region) ``` -------------------------------- ### Create Snapshot Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Demonstrates how to create a snapshot from a running instance using the SnapshotService.Create method. ```go snapshot, _, err := client.Snapshot.Create(ctx, &govultr.SnapshotReq{ InstanceID: instanceID, Description: "pre-upgrade backup", }) if err != nil { panic(err) } fmt.Printf("Snapshot created: %s\n", snapshot.ID) ``` -------------------------------- ### Get Domain Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md Retrieves information about a specific domain by its name. The response includes domain details and DNSSec status. ```go domain, _, err := client.Domain.Get(ctx, "example.com") if err != nil { panic(err) } fmt.Printf("Domain: %s, DNSSec: %s\n", domain.Domain, domain.DNSSec) ``` -------------------------------- ### Mass Start Instances Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Starts multiple Vultr instances simultaneously. ```APIDOC ## POST /v2/instances/start ### Description Starts multiple Vultr instances simultaneously. ### Method POST ### Endpoint /v2/instances/start ### Parameters #### Request Body - **instanceList** ([]string) - Required - A list of instance IDs to start. ### Response #### Success Response (200) - **error** (error) - An error if the mass start operation failed. ``` -------------------------------- ### List Backups Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Demonstrates how to list all backups on an account and print their details. Ensure proper error handling. ```go backups, meta, _, err := client.Backup.List(ctx, nil) if err != nil { panic(err) } for _, backup := range backups { sizeGB := backup.Size / (1024 * 1024 * 1024) fmt.Printf("%s: %s (%d GB) - %s\n", backup.ID, backup.DateCreated, sizeGB, backup.Status) } ``` -------------------------------- ### Start Instance Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Powers on a stopped instance. ```APIDOC ## Start Instance Powers on an instance. ### Method POST ### Endpoint `/v2/instances/{instanceID}/start` ### Parameters #### Path Parameters - **instanceID** (string) - Required - Instance UUID ### Request Example ```go err := client.Instance.Start(ctx, instanceID) ``` ``` -------------------------------- ### Context with Cancellation in Go Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md This example shows how to create a context that can be cancelled manually, for example, after a certain duration. ```go // With cancellation ctx, cancel := context.WithCancel(context.Background()) goo func() { Sleep(5 * time.Second) cancel() // Cancel after 5 seconds }() instance, _, err := client.Instance.Get(ctx, id) ``` -------------------------------- ### IPv4 Subnet Examples Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md Examples demonstrating how to specify IPv4 addresses and network ranges for subnets. Use SubnetSize 32 for a single IP, 0 for all IPs, or a CIDR range for a network. ```go // Single IP Subnet: "203.0.113.1" SubnetSize: 32 // Network range Subnet: "203.0.113.0" SubnetSize: 24 // 203.0.113.0 - 203.0.113.255 // All IPs Subnet: "0.0.0.0" SubnetSize: 0 ``` -------------------------------- ### List VPCs Go Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Lists all VPCs associated with the account. The `ListOptions` can be nil to fetch all VPCs. ```go vpcs, meta, _, err := client.VPC.List(ctx, nil) if err != nil { panic(err) } fmt.Printf("Total VPCs: %d\n", meta.Total) for _, vpc := range vpcs { fmt.Printf("- %s: %s (%s)\n", vpc.ID, vpc.Description, vpc.Region) ``` -------------------------------- ### Create a Vultr VPS Instance Source: https://github.com/vultr/govultr/blob/master/README.md Example of creating a new VPS instance with specified options such as label, OS, plan, and region. ```go 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) } ``` -------------------------------- ### List Snapshots Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Lists all snapshots on the account, with support for filtering by description using ListOptions. ```go opts := &govultr.ListOptions{ PerPage: 50, Description: "backup", // Filter by description } snapshots, meta, _, err := client.Snapshot.List(ctx, opts) if err != nil { panic(err) } fmt.Printf("Found %d matching snapshots\n", len(snapshots)) for _, snap := range snapshots { fmt.Printf("- %s: %s (%s)\n", snap.ID, snap.Description, snap.Status) } ``` -------------------------------- ### Create Domain Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md Registers a new domain with Vultr DNS or adds a domain delegation. Ensure the DomainReq struct is populated with necessary details. ```go req := &govultr.DomainReq{ Domain: "example.com", IP: "203.0.113.1", DNSSec: "enabled", } domain, _, err := client.Domain.Create(ctx, req) if err != nil { panic(err) } fmt.Printf("Domain created: %s\n", domain.Domain) ``` -------------------------------- ### Import Govultr Package Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md Import the main Govultr package to start using its functionalities. ```go import "github.com/vultr/govultr/v3" ``` -------------------------------- ### List VPC Attachments Go Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Lists all resources, such as instances, attached to a specific VPC. The `ListOptions` can be nil. ```go attachments, _, _, err := client.VPC.ListAttachments(ctx, vpcID, nil) if err != nil { panic(err) } for _, att := range attachments { fmt.Printf("- %s (%s): %s, IP: %s\n", att.ID, att.Type, att.MACAddress, att.IP.V4) ``` -------------------------------- ### Create VPC Go Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Creates a new Virtual Private Cloud network. Ensure the context and VPC creation parameters are correctly provided. ```go vpc, _, err := client.VPC.Create(ctx, &govultr.VPCReq{ Region: "ewr", Description: "Production VPC", V4Subnet: "10.0.0.0", V4SubnetMask: 24, }) if err != nil { panic(err) } fmt.Printf("Created VPC: %s\n", vpc.ID) ``` -------------------------------- ### IPv6 Subnet Examples Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md Examples for configuring IPv6 single IP addresses and network ranges. SubnetSize 128 is for a single IP, 0 for all IPs, and 64 for a typical network range. ```go // Single IP Subnet: "2001:db8::1" SubnetSize: 128 // Network range Subnet: "2001:db8::" SubnetSize: 64 // All IPs Subnet: "::" SubnetSize: 0 ``` -------------------------------- ### List Domains Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md Lists all domains on the account, with optional pagination. The output includes total domain count and creation dates. ```go opts := &govultr.ListOptions{PerPage: 50} domains, meta, _, err := client.Domain.List(ctx, opts) if err != nil { panic(err) } fmt.Printf("Total domains: %d\n", meta.Total) for _, d := range domains { fmt.Printf("- %s (created: %s)\n", d.Domain, d.DateCreated) } ``` -------------------------------- ### Configure a Firewall Group and Rule Source: https://github.com/vultr/govultr/blob/master/_autodocs/00-START-HERE.md Create a firewall group and then add a specific rule to it. This example sets up a rule for TCP traffic on port 80. ```go group, _, err := client.FirewallGroup.Create(ctx, &govultr.FirewallGroupReq{ Description: "web-servers", }) client.FirewallRule.Create(ctx, group.ID, &govultr.FirewallRuleReq{ IPType: "v4", Protocol: "tcp", Port: "80", Subnet: "0.0.0.0", SubnetSize: 0, }) ``` -------------------------------- ### Create Snapshot From URL Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Creates a snapshot from a remote URL using the SnapshotService.CreateFromURL method. ```go snapshot, _, err := client.Snapshot.CreateFromURL(ctx, &govultr.SnapshotURLReq{ URL: "https://example.com/images/custom-os.iso", Description: "custom-image", }) if err != nil { panic(err) } ``` -------------------------------- ### Update VPC Description Go Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Updates the description of an existing VPC. The VPC must exist and be accessible. ```go err := client.VPC.Update(ctx, vpcID, "Updated production network") if err != nil { panic(err) } ``` -------------------------------- ### Start Vultr Instance Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Powers on a Vultr instance. This operation is used to resume a halted or stopped instance. ```go err := client.Instance.Start(ctx, instanceID) ``` -------------------------------- ### Instance Power Operations Source: https://github.com/vultr/govultr/blob/master/_autodocs/services-overview.md Control the power state of an instance. Use Start, Halt, or Reboot methods with the instance ID. ```go err := client.Instance.Start(ctx, instanceID) err := client.Instance.Halt(ctx, instanceID) err := client.Instance.Reboot(ctx, instanceID) ``` -------------------------------- ### Get Snapshot Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Retrieves details for a specific snapshot using its ID with the SnapshotService.Get method. ```go snapshot, _, err := client.Snapshot.Get(ctx, snapshotID) if err != nil { panic(err) } sizeGB := snapshot.Size / (1024 * 1024 * 1024) fmt.Printf("Size: %d GB, Status: %s\n", sizeGB, snapshot.Status) ``` -------------------------------- ### Basic GoVultr Client Setup Source: https://github.com/vultr/govultr/blob/master/_autodocs/quick-start.md Set up a basic GoVultr client by retrieving your API key from environment variables and creating an authenticated HTTP client. Optional configurations for rate limiting and user agent are also shown. ```go package main import ( "context" "os" "github.com/vultr/govultr/v3" "golang.org/x/oauth2" ) func main() { // Get API key from environment apiKey := os.Getenv("VULTR_API_KEY") // Create OAuth2 token source config := &oauth2.Config{} ctx := context.Background() ts := config.TokenSource(ctx, &oauth2.Token{AccessToken: apiKey}) // Create Vultr client httpClient := oauth2.NewClient(ctx, ts) client := govultr.NewClient(httpClient) // Optional: Configure client client.SetRateLimit(500 * time.Millisecond) client.SetUserAgent("my-app/1.0.0") // Now you can use the client... } ``` -------------------------------- ### Set Up a Domain Source: https://github.com/vultr/govultr/blob/master/_autodocs/00-START-HERE.md Create a new domain entry by providing the domain name and its associated IP address. ```go domain, _, err := client.Domain.Create(ctx, &govultr.DomainReq{ Domain: "example.com", IP: "203.0.113.1", }) ``` -------------------------------- ### Get SOA Record for Domain Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md Retrieves the Start of Authority (SOA) record for a specified domain. Requires the domain name as input. ```go func (d *DomainServiceHandler) GetSoa(ctx context.Context, domain string) (*Soa, *http.Response, error) ``` ```go type Soa struct { NSPrimary string `json:"nsprimary,omitempty"` Email string `json:"email,omitempty"` } ``` ```go soa, _, err := client.Domain.GetSoa(ctx, "example.com") if err != nil { panic(err) } fmt.Printf("NS Primary: %s, Email: %s\n", soa.NSPrimary, soa.Email) ``` -------------------------------- ### Get Firewall Rule Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/firewall-service.md Retrieves a specific firewall rule using its group ID and rule ID. Handles potential errors during the retrieval process. ```go rule, _, err := client.FirewallRule.Get(ctx, groupID, 1) if err != nil { panic(err) } fmt.Printf("Rule: %s %s/%d:%s\n", rule.Action, rule.Subnet, rule.SubnetSize, rule.Port) ``` -------------------------------- ### Successful Response Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md This is an example of a successful API response, typically returning a 200-204 status code. ```json { "instance": { "id": "uuid", "label": "name", ... } } ``` -------------------------------- ### Initialize Govultr Client with API Key Source: https://github.com/vultr/govultr/blob/master/_autodocs/00-START-HERE.md Set up the Govultr client using an API key for authentication. This involves creating an OAuth2 token source. ```go import "golang.org/x/oauth2" config := &oauth2.Config{} ts := config.TokenSource(ctx, &oauth2.Token{AccessToken: apiKey}) client := govultr.NewClient(oauth2.NewClient(ctx, ts)) ``` -------------------------------- ### Error Response Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md This is an example of an API error response, indicating an issue with the request, typically with a 4xx or 5xx status code. ```json { "error": "Error message describing the issue" } ``` -------------------------------- ### Get Resource Source: https://github.com/vultr/govultr/blob/master/_autodocs/services-overview.md Retrieve a single resource by its ID. This operation uses a GET request and requires the resource's unique identifier. ```go resource, resp, err := client.Service.Get(ctx, resourceID) ``` -------------------------------- ### Initialize GoVultr Client with Authentication Source: https://github.com/vultr/govultr/blob/master/README.md Set up the Vultr client using an API key from an environment variable. The client can be configured with a custom base URL, user agent, and rate limit delay. ```go 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)) // Optional changes _ = vultrClient.SetBaseURL("https://api.vultr.com") vultrClient.SetUserAgent("mycool-app") vultrClient.SetRateLimit(500) } ``` -------------------------------- ### Example: Retrieve and Print Bandwidth Statistics Source: https://github.com/vultr/govultr/blob/master/_autodocs/account-service.md Demonstrates how to call the GetBandwidth function and then print the statistics for each period using a helper function. Error handling is included. ```go bw, _, err := client.Account.GetBandwidth(ctx) if err != nil { panic(err) } printPeriod := func(name string, period govultr.AccountBandwidthPeriod) { fmt.Printf("\n%s (%s to %s):\n", name, period.TimestampStart, period.TimestampEnd) fmt.Printf(" Incoming: %d GB\n", period.GBIn) fmt.Printf(" Outgoing: %d GB\n", period.GBOut) fmt.Printf(" Instances: %d (%d hours)\n", period.TotalInstanceCount, period.TotalInstanceHours) fmt.Printf(" Credits: %d (free) + %d (purchased)\n", period.FreeBandwidthCredits, period.PurchasedBandwidthCredits) if period.Overage > 0 { fmt.Printf(" Overage: %.2f GB @ $%.4f/GB = $%.2f\n", period.Overage, period.OverageUnitCost, period.OverageCost) } } printPeriod("Previous Month", bw.PreviousMonth) printPeriod("Current Month (to date)", bw.CurrentMonthToDate) printPeriod("Current Month (projected)", bw.CurrentMonthProjected) ``` -------------------------------- ### Get Snapshot Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Retrieves details of a specific snapshot. ```APIDOC ## Get Snapshot ### Description Retrieves details of a specific snapshot. ### Method GET ### Endpoint /v1/snapshots/{snapshot_id} ### Parameters #### Path Parameters - **snapshot_id** (string) - Required - The ID of the snapshot to retrieve. ### Response #### Success Response (200) - **snapshot** (object) - The snapshot object. - **id** (string) - The ID of the snapshot. - **status** (string) - The status of the snapshot. - **size** (integer) - The size of the snapshot in bytes. - **description** (string) - The description of the snapshot. ### Response Example ```json { "id": "snap-xxxxxxxxxxxxxxxxx", "status": "complete", "size": 10737418240, "description": "pre-maintenance-snapshot" } ``` ``` -------------------------------- ### Retrieve Available Instance Upgrades Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Lists all available upgrade options for an instance, including plans, operating systems, and applications. ```go func (i *InstanceServiceHandler) GetUpgrades(ctx context.Context, instanceID string) (*Upgrades, *http.Response, error) ``` -------------------------------- ### Create and Configure Firewall Source: https://github.com/vultr/govultr/blob/master/_autodocs/firewall-service.md This Go code demonstrates a complete workflow for creating a firewall group, adding multiple rules to it, and then viewing the configured firewall and its rules. Ensure you have initialized the Vultr client with your API key and an HTTP client. ```go package main import ( "context" "github.com/vultr/govultr/v3" ) func main() { ctx := context.Background() client := govultr.NewClient(httpClient) // Step 1: Create firewall group group, _, _ := client.FirewallGroup.Create(ctx, &govultr.FirewallGroupReq{ Description: "production-servers", }) // Step 2: Add rules rules := []*govultr.FirewallRuleReq{ { IPType: "v4", Protocol: "tcp", Port: "22", Subnet: "0.0.0.0", SubnetSize: 0, Notes: "SSH from anywhere", }, { IPType: "v4", Protocol: "tcp", Port: "80", Subnet: "0.0.0.0", SubnetSize: 0, Notes: "HTTP from anywhere", }, { IPType: "v4", Protocol: "tcp", Port: "443", Subnet: "0.0.0.0", SubnetSize: 0, Notes: "HTTPS from anywhere", }, } for _, rule := range rules { client.FirewallRule.Create(ctx, group.ID, rule) } // Step 3: View firewall configured, _, _ := client.FirewallGroup.Get(ctx, group.ID) fmt.Printf("Firewall configured with %d rules\n", configured.RuleCount) // Step 4: List all rules ruleList, _, _, _ := client.FirewallRule.List(ctx, group.ID, nil) for _, r := range ruleList { fmt.Printf("Rule %d: %s %s:%s from %s/%d\n", r.ID, r.Protocol, r.Port, r.IPType, r.Subnet, r.SubnetSize) } } ``` -------------------------------- ### Get Domain Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md Retrieves information about a specific domain by its name. ```APIDOC ## GET /v2/domains/{domain} ### Description Retrieves information about a specific domain. ### Method GET ### Endpoint /v2/domains/{domain} ### Parameters #### Path Parameters - **domain** (string) - yes - Domain name ### Response #### Success Response (200) - **Domain** (*Domain) - Domain details including creation date and DNSSec status #### Response Example ```json { "domain": "example.com", "id": "1234567890abcdef", "date_created": "2023-01-01T10:00:00Z", "dns_sec": "enabled" } ``` ``` -------------------------------- ### Create Domain and Add DNS Records Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md This Go code snippet demonstrates how to create a new domain, add 'A', 'MX', and 'TXT' records, and enable DNSSEC using the Vultr Go SDK. It requires the `context`, `fmt`, and `github.com/vultr/govultr/v3` packages. ```go package main import ( "context" "fmt" "github.com/vultr/govultr/v3" ) func main() { ctx := context.Background() client := govultr.NewClient(httpClient) // Create domain domain, _, err := client.Domain.Create(ctx, &govultr.DomainReq{ Domain: "example.com", IP: "203.0.113.1", }) if err != nil { panic(err) } fmt.Printf("Domain created: %s\n", domain.Domain) // Add A records www, _, _ := client.DomainRecord.Create(ctx, "example.com", &govultr.DomainRecordReq{ Type: "A", Name: "www", Data: "203.0.113.1", TTL: govultr.IntToIntPtr(3600), }) // Add MX record client.DomainRecord.Create(ctx, "example.com", &govultr.DomainRecordReq{ Type: "MX", Data: "mail.example.com", Priority: govultr.IntToIntPtr(10), TTL: govultr.IntToIntPtr(3600), }) // Add TXT record (SPF) client.DomainRecord.Create(ctx, "example.com", &govultr.DomainRecordReq{ Type: "TXT", Data: "v=spf1 include:_spf.google.com ~all", TTL: govultr.IntToIntPtr(3600), }) // Enable DNSSec client.Domain.Update(ctx, "example.com", "enabled") // List all records records, _, _, _ := client.DomainRecord.List(ctx, "example.com", nil) fmt.Printf("Total records: %d\n", len(records)) } ``` -------------------------------- ### GetSoa Source: https://github.com/vultr/govultr/blob/master/_autodocs/domain-service.md Retrieves the SOA (Start of Authority) record for a specified domain. ```APIDOC ## GetSoa /v2/domains/{domain}/soa ### Description Retrieves the SOA (Start of Authority) record for a domain. ### Method GET ### Endpoint /v2/domains/{domain}/soa ### Parameters #### Path Parameters - **domain** (string) - Required - The domain name to retrieve the SOA record for. ### Response #### Success Response (200) - **NSPrimary** (string) - Primary nameserver. - **Email** (string) - SOA email address. ### Response Example ```json { "nsprimary": "ns1.vultr.com", "email": "hostmaster@example.com" } ``` ``` -------------------------------- ### Get Instance Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Retrieves details about a specific instance using its ID. ```APIDOC ## Get Instance ### Description Retrieves details about a specific instance. ### Method GET ### Endpoint /v2/instances/{instanceID} ### Parameters #### Path Parameters - **instanceID** (string) - Required - Instance UUID ### Request Example ```go instance, _, err := client.Instance.Get(ctx, "12345678-1234-1234-1234-123456789012") if err != nil { panic(err) } fmt.Printf("Status: %s, IP: %s\n", instance.Status, instance.MainIP) ``` ### Response #### Success Response (200) - **Instance** (*Instance) - Instance details #### Error Handling - Error if not found or unauthorized ``` -------------------------------- ### Get Upgrades Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Retrieves available upgrade options for a Vultr instance. ```APIDOC ## GET /v2/instances/{instanceID}/upgrades ### Description Retrieves available upgrade options for a Vultr instance. ### Method GET ### Endpoint /v2/instances/{instanceID}/upgrades ### Parameters #### Path Parameters - **instanceID** (string) - Required - The ID of the instance. ### Response #### Success Response (200) - **upgrades** (*Upgrades) - The available upgrades object. - **response** (*http.Response) - The HTTP response object. - **error** (error) - An error if the retrieval failed. ``` -------------------------------- ### Implementing Pagination for Instance Listing Source: https://github.com/vultr/govultr/blob/master/_autodocs/quick-start.md To retrieve all instances, especially when there are more than the `PerPage` limit, you must handle pagination by checking for the next page link in the metadata. ```go // Wrong - may miss instances on second page instances, _, _, _ := client.Instance.List(ctx, &govultr.ListOptions{PerPage: 50}) // Only gets first 50 // Right - handle pagination opts := &govultr.ListOptions{PerPage: 50} for { instances, meta, _, _ := client.Instance.List(ctx, opts) // Process instances... if meta.Links.Next == "" { break } opts.Cursor = meta.Links.Next } ``` -------------------------------- ### Get Instance Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Retrieves details for a specific Vultr instance by its ID. ```APIDOC ## GET /v2/instances/{instanceID} ### Description Retrieves details for a specific Vultr instance by its ID. ### Method GET ### Endpoint /v2/instances/{instanceID} ### Parameters #### Path Parameters - **instanceID** (string) - Required - The ID of the instance to retrieve. ### Response #### Success Response (200) - **instance** (*Instance) - The retrieved instance object. - **response** (*http.Response) - The HTTP response object. - **error** (error) - An error if the retrieval failed. ``` -------------------------------- ### Get Firewall Group Source: https://github.com/vultr/govultr/blob/master/_autodocs/firewall-service.md Retrieves a specific firewall group by its ID. ```APIDOC ## GET /v2/firewalls/{fwGroupID} ### Description Retrieves a firewall group by ID. ### Method GET ### Endpoint /v2/firewalls/{fwGroupID} ### Parameters #### Path Parameters - **fwGroupID** (string) - Required - The ID of the firewall group to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the firewall group. - **description** (string) - The description of the firewall group. - **rule_count** (integer) - The number of rules in the firewall group. - **max_rule_count** (integer) - The maximum number of rules allowed. #### Response Example ```json { "id": "fwp-1234567890abcdef", "description": "web-servers", "rule_count": 5, "max_rule_count": 50 } ``` ``` -------------------------------- ### Create a Cloud Server Source: https://github.com/vultr/govultr/blob/master/_autodocs/00-START-HERE.md Use this snippet to create a new cloud server instance. Specify the region, plan, label, and operating system ID. ```go instance, _, err := client.Instance.Create(ctx, &govultr.InstanceCreateReq{ Region: "ewr", Plan: "vc2-1c-2gb", Label: "my-server", OsID: 387, // Ubuntu 22.04 }) ``` -------------------------------- ### Delete Snapshot Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Deletes a snapshot using its ID with the SnapshotService.Delete method. ```go err := client.Snapshot.Delete(ctx, snapshotID) if err != nil { panic(err) } ``` -------------------------------- ### Get VPC Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Retrieves detailed information about a specific VPC using its ID. ```APIDOC ## Get VPC ### Description Retrieves details about a specific VPC. ### Method GET ### Endpoint /v2/vpcs/{vpcID} ### Parameters #### Path Parameters - **vpcID** (string) - Required - The unique identifier of the VPC. ### Response #### Success Response (200) - **ID** (string) - VPC ID (UUID) - **Region** (string) - Region where VPC is located - **Description** (string) - VPC description - **V4Subnet** (string) - IPv4 subnet network address - **V4SubnetMask** (int) - Subnet mask size - **DateCreated** (string) - ISO 8601 creation timestamp ### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "region": "ewr", "description": "Production VPC", "v4_subnet": "10.0.0.0", "v4_subnet_mask": 24, "date_created": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get VPC Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md Retrieves details of a specific Virtual Private Cloud network. ```APIDOC ## Get VPC ### Description Retrieves details of a specific Virtual Private Cloud network. ### Method GET ### Endpoint /v2/vpcs/{vpcID} ### Parameters #### Path Parameters - **vpcID** (string) - Required - The ID of the VPC to retrieve. ### Response #### Success Response (200) - **VPC** (*VPC) - The VPC object. - **http.Response** (*http.Response) - The HTTP response object. #### Response Example ```json { "example": "response body for a VPC" } ``` ``` -------------------------------- ### List Firewall Rules Example Source: https://github.com/vultr/govultr/blob/master/_autodocs/firewall-service.md Lists all firewall rules within a specified firewall group. It iterates through the returned rules and prints their details, indicating whether they allow or drop traffic. ```go rules, meta, _, err := client.FirewallRule.List(ctx, groupID, nil) if err != nil { panic(err) } for _, r := range rules { action := "✓ Allow" if r.Action == "drop" { action = "✗ Drop" } fmt.Printf("%s %s %s/%d:%s\n", action, r.Protocol, r.Subnet, r.SubnetSize, r.Port) } ``` -------------------------------- ### Create VPC, NAT Gateway, Firewall Rule, and Port Forwarding Source: https://github.com/vultr/govultr/blob/master/_autodocs/vpc-service.md This Go code demonstrates a complete workflow for setting up a VPC with a NAT gateway, configuring a firewall rule for HTTPS traffic, and establishing SSH port forwarding. ```go // Create VPC vpc, _, err := client.VPC.Create(ctx, &govultr.VPCReq{ Region: "ewr", Description: "private-network", V4Subnet: "10.0.0.0", V4SubnetMask: 24, }) // Create NAT gateway gateway, _, err := client.VPC.CreateNATGateway(ctx, vpc.ID, &govultr.NATGatewayReq{ Label: "outbound-nat", }) // Create firewall rule (allow all HTTPS) client.VPC.CreateNATGatewayFirewallRule(ctx, vpc.ID, gateway.ID, &govultr.NATGatewayFirewallRuleCreateReq{ Protocol: "tcp", Port: "443", Subnet: "10.0.0.0", SubnetSize: 8, }) // Create port forward (SSH) client.VPC.CreateNATGatewayPortForwardingRule(ctx, vpc.ID, gateway.ID, &govultr.NATGatewayPortForwardingRuleReq{ Name: "SSH", Protocol: "tcp", ExternalPort: 2222, InternalIP: "10.0.1.5", InternalPort: 22, Enabled: govultr.BoolToBoolPtr(true), }) ``` -------------------------------- ### Get User Data Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Retrieves the user data associated with a Vultr instance. ```APIDOC ## GET /v2/instances/{instanceID}/user_data ### Description Retrieves the user data associated with a Vultr instance. ### Method GET ### Endpoint /v2/instances/{instanceID}/user_data ### Parameters #### Path Parameters - **instanceID** (string) - Required - The ID of the instance. ### Response #### Success Response (200) - **userData** (*UserData) - The user data object. - **response** (*http.Response) - The HTTP response object. - **error** (error) - An error if the retrieval failed. ``` -------------------------------- ### Get Backup Schedule Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Retrieves the current backup schedule for a given instance. ```APIDOC ## Get Backup Schedule ### Description Retrieves the current backup schedule for a given instance. ### Method GET ### Endpoint /v1/instances/{instance_id}/backup-schedule ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to get the backup schedule for. ### Response #### Success Response (200) - **schedule** (object) - The backup schedule details. - **type** (string) - The type of backup schedule (e.g., "daily", "weekly", "monthly"). - **hour** (integer) - The hour (UTC) when the backup should be performed. - **dow** (integer) - The day of the week (0-6, 0=Sunday) for weekly schedules. - **dom** (integer) - The day of the month (1-31) for monthly schedules. ### Response Example ```json { "type": "weekly", "hour": 2, "dow": 0 } ``` ``` -------------------------------- ### Create Resource Source: https://github.com/vultr/govultr/blob/master/_autodocs/services-overview.md Use this pattern to create a new resource. It requires a context, and a request object specific to the resource being created. ```go resource, resp, err := client.Service.Create(ctx, createReq) ``` -------------------------------- ### Get Backup Details Source: https://github.com/vultr/govultr/blob/master/_autodocs/backup-snapshot-service.md Retrieves details about a specific backup using its ID. ```APIDOC ## GET /v2/backups/{backupID} ### Description Retrieves details about a specific backup. ### Method GET ### Endpoint /v2/backups/{backupID} ### Parameters #### Path Parameters - **backupID** (string) - Required - The ID of the backup to retrieve. ### Request Example ```go backup, _, err := client.Backup.Get(ctx, backupID) if err != nil { panic(err) } fmt.Printf("Backup: %s, Size: %d bytes\n", backup.ID, backup.Size) ``` ### Response #### Success Response (200) - **Backup** - A Backup object with details. #### Response Example ```json { "ID": "2d3a4b5c-6d7e-8f9a-0b1c-2d3e4f5a6b7c", "DateCreated": "2023-10-27T10:00:00Z", "Description": "My first backup", "Size": 10737418240, "Status": "complete", "InstanceID": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Testing Govultr Client with Mock Transport Source: https://github.com/vultr/govultr/blob/master/_autodocs/reference-guide.md Demonstrates how to create a test client and mock the HTTP transport for testing purposes. This is useful for isolating the client's logic from actual network requests and testing error handling. ```go // Create test client testClient := govultr.NewClient(nil) // Mock the HTTP transport mockClient := &http.Client{ Transport: &mockTransport{}, } testClient = govultr.NewClient(mockClient) // Test error handling _, _, err := testClient.Instance.Get(context.Background(), "invalid") ``` -------------------------------- ### Initialize Vultr Go Client Source: https://github.com/vultr/govultr/blob/master/_autodocs/services-overview.md Instantiate the main Client struct with an HTTP client. Services are then accessible as fields on this client. ```go client := govultr.NewClient(httpClient) // Services available as fields: client.Instance // InstanceService client.VPC // VPCService client.Domain // DomainService client.Database // DatabaseService // ... etc ``` -------------------------------- ### Manage Instance IPv4 Operations Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Demonstrates creating, listing, and deleting IPv4 addresses for an instance. Note the use of `govultr.BoolToBoolPtr` for boolean parameters. ```go ipv4, _, err := client.Instance.CreateIPv4(ctx, instanceID, govultr.BoolToBoolPtr(false)) ips, _, _, err := client.Instance.ListIPv4(ctx, instanceID, nil) err = client.Instance.DeleteIPv4(ctx, instanceID, "203.0.113.1") ``` -------------------------------- ### Get Instance Neighbors Source: https://github.com/vultr/govultr/blob/master/_autodocs/instance-service.md Lists the IDs of neighbor instances that are on the same host as the specified instance. ```APIDOC ## GET /v1/instances/{instance_id}/neighbors ### Description Lists neighbor instance IDs on the same host. ### Method GET ### Endpoint /v1/instances/{instance_id}/neighbors ### Parameters #### Path Parameters - **instance_id** (string) - Required - The ID of the instance to find neighbors for. ### Response #### Success Response (200) - **neighbors** (array) - A list of strings, where each string is the ID of a neighbor instance. ### Response Example ```json { "neighbors": [ "instance-id-abc", "instance-id-def" ] } ``` ```