How To Use The Vultr Go Library To Get Server Info

Updated on September 27, 2019
How To Use The Vultr Go Library To Get Server Info header image

Introduction

The official Vultr Go library can be used to interact with the Vultr API. The Vultr API allows you to control the resources associated with your account, including servers, dns, firewall, snapshots, network, and more. This tutorial will give an introduction to using the official Go API client by creating a simple application to get information about your servers.

Prerequisites

  • A computer running Windows, Linux, or macOS with Go 1.12+ installed.
  • Basic programming knowledge.
  • Optional: An IDE supporting Go (for example Visual Studio Code, emacs, or Atom).

Goals

  • To learn how to use the official Vultr API library.
  • To write a program to view server information.

Step 1: Creating the project

First, we will start by creating a new module (project). Usually, you would use the URL to a repository for your code as the module name, but that is beyond the scope of this tutorial. For now, we will use serverinfo as the module name.

To create the project, run the following commands:

# Create the folder in the current directory.
mkdir serverinfo

# Enter the new folder.
cd serverinfo

# Initialize the module.
go mod init serverinfo

Step 2: Downloading the library

Next, we will download the API library from GitHub (a code hosting site). To download libraries, you need to use the go get command. This will automatically download the library and its dependencies while adding it to the go.mod file. In the same terminal you opened earlier, enter the following command:

go get github.com/vultr/govultr

Step 3: Getting your API key

To use the API client, you will need your API key. You can retrieve your API key from the API tab of the Account section of your Dashboard. You will also need to authorize your IP address to use the API key. You can find your IP address by going to ifconfig.me. Note that you are looking for your public IP, not your private one. Your private IP is what you would find in your network settings on your computer, and is in one of the following CIDR ranges: 10.0.0.0/8, 172.16.0.0/12, or 192.168.0.0/16.

Once you have your IP address, add it under the Access Control section. In the box after the /, type 32. /32 is a netmask meaning 255.255.255.255. This means that only your IP is included in the range.

Warning: Protect your API key like you would protect your password. The API key has access to your entire account, including billing, servers, and storage.

Step 4: Creating the program file

Now, we are going to start working on the program. Open up the folder we created in your choice of editor, and create a file named main.go.

Inside the file, type or copy-paste the following code:

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/vultr/govultr"
)

func main() {

}

The package main tells Go that we are creating a command, not a library. The import statement declares the dependencies we will be using. func main() is the function called when we run our program.

Step 5: Initializing the API client

The next step is to initialize the API client. To do this, we need to use the govultr.NewClient(http.Client, string) function. Add the following code inside the main() function:

client := govultr.NewClient(nil, "YOURAPIKEY")

Replace YOURAPIKEY with the API key you retrieved earlier.

Let's look at this code a bit closer. On the left side of the :=, we have client. That is the name of a variable. A variable stores values. On the right side, we have a function call to govultr.NewClient. The first parameter is nil, because we don't need to change the default HTTP client. The second parameter is the API key we are using to authenticate ourselves. The := operator assigns the right-side to the left side, in this case, the result of the function call to client.

Step 6: Using the API

Our program still doesn't do anything yet. To make it useful, we are going to retrieve information about our servers from Vultr. We will use the govultr.Client.Server.List(context.Context) ([]govultr.Server, error) function. Add the following code at the end of the main() function:

servers, err := client.Server.List(context.Background())
if err != nil {
    fmt.Fprintf(os.Stderr, "Error: %v\n", err)
    os.Exit(1)
}

In this code, we are calling the API function to retrieve the server information. Don't worry about the meaning of the context yet, as that is a more advanced topic. For now, all we need to know is that the context controls how the API client runs. context.Background() returns an empty context. After we retrieve the server information into the two variables, servers and err, we check if there was an error. If so, we tell inform the user of the error and exit with code 1 (error).

Step 7: Showing the information

Now that we have an array of servers in the servers variable ([]govultr.Server), we can actually display it. Add the following code at the end of the main() function:

fmt.Println("Servers:")
for _, server := range servers {
    fmt.Printf("  %s (%s) - %s - $%s pending charges - %.2f/%s GB bandwidth\n",
        server.Label,
        server.MainIP,
        server.Location,
        server.PendingCharges,
        server.CurrentBandwidth,
        server.AllowedBandwidth,
    )
}

First, we print (display) a header, Servers:. Then, we loop over the servers array, ignoring the index by assigning it to _, and assigning the current server to the server variable. Inside the loop, we display the server's label, IP address, location, pending charges, current bandwidth, and allowed bandwidth. To do this efficently, we use format strings, the string which looks like " %s (%s) - %s - $%s pending charges - %.2f/%s GB bandwidth\n". The %s means to substitute the next string, while the %.2f means to print the next float (decimal number) rounded to 2 decimal places. The rest of the format string is printed literally (as-is).

Step 8: Running

At this point, your code should look like the following:

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/vultr/govultr"
)

func main() {
    client := govultr.NewClient(nil, "YOURAPIKEY")

    servers, err := client.Server.List(context.Background())
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", err)
        os.Exit(1)
    }

    fmt.Println("Servers:")
    for _, server := range servers {
        fmt.Printf("  %s (%s) - %s - $%s pending charges - %.2f/%s GB bandwidth\n",
            server.Label,
            server.MainIP,
            server.Location,
            server.PendingCharges,
            server.CurrentBandwidth,
            server.AllowedBandwidth,
        )
    }
}

We can now run the code. Return to the terminal we opened earlier and enter the command go run. The output will resemble the following:

Servers:
  server1 (198.51.100.4) - New Jersey - $3.70 pending charges - 17.64/1000 GB bandwidth
  server2 (198.51.100.9) - Toronto - $1.70 pending charges - 3.24/500 GB bandwidth

If you receive an error, ensure your API key and IP address are correct.

Conclusion

At this point, you will have successfully learned the basics of how to use the official API client and written a program which will display information about the servers in your account.

Further steps

From here, you can do much more. For example, you could write a program to provision a new server when you are low on memory. You could write an app to automatically upgrade your server when you are low on bandwidth or storage. You could even write a tool to automatically update DNS records based on your current IP.

For more information on the govultr library, you can find the govultr library documentation on godoc.

govultr is an open-source project. If you find any bugs in govultr, you can report them on GitHub. You can also contribute to the code directly by submitting a pull request.