This article provides the steps necessary to write and run a simple Go program
that queries the Red Canary API.
Estimated procedure time: 10 minutes.
Prerequisites
Before you run any code, make sure you have the following:
- Your API key. If you don't have your API key, or you need to reset an old key, see Reset your API key in the Red Canary Help Center.
- The latest recommended version of Go. To download Go, see https://go.dev.
Create your Go program
Create a Go program called example.go
, which fetches a list of endpoints from a subdomain.
- In your working directory, create a new file called
example.go
, and then copy the following code into it.
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
// Create a client with a 3 second timeout.
client := &http.Client{
Timeout: 3 * time.Second,
}
// Create a GET request.
request, err := http.NewRequest("GET", "https://<subdomain>.my.redcanary.co/openapi/v3/endpoints", nil)
if err != nil {
log.Fatalf("Something went wrong: %s", err.Error())
}
// Add the API key to the request.
request.Header.Set("X-Api-Key", "<API key>")
// Send the request and receive a response.
response, err := client.Do(request)
if err != nil {
log.Fatalf("Something went wrong: %s", err.Error())
}
// Parse and print the response.
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatalf("Something went wrong: %s", err.Error())
}
fmt.Println(string(body))
} - In
example.go
, replace<subdomain>
with the Red Canary subdomain you want to query. - In
example.go
, replace<API key>
with your API key. - Save
example.go
.
Build and run the example
Run your example with the following command.
go run example.go
The program should print a JSON object containing the first page of endpoints associated with the subdomain.
Customize your request with parameters
You can use HTTP parameters to customize the results of your request. Visit the Red Canary API docs for a list of supported parameters for each API endpoint.
Example: Limit the number of endpoints returned
Limit the number of endpoints returned by example.go
using the per_page
parameter.
- Open
example.go
, and then find the URL passed tohttp.NewRequest()
. - Add the following to the end of the URL:
?per_page=1
This sets the number of requested endpoints to one. - Save
example.go
, and then run the example. The program should print a JSON object containing exactly one endpoint.
Comments
0 comments
Please sign in to leave a comment.