- 16 Jul 2024
- 1 Minute to read
- PDF
Go Example
- Updated on 16 Jul 2024
- 1 Minute to read
- PDF
Follow these necessary steps to write and run a simple Go program that queries the Red Canary API.
Prerequisites
Before running any code, ensure you have the following:
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://.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", "") // 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 with the Red Canary subdomain you want to query.In
example.go
, replace 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.