Google DNS APIs allow developers to perform DNS queries and get JSON responses. In this article, we'll walk through how to make a request to these APIs using the Go programming language.
Start by creating a directory for your Go project. For example:
mkdir google-dns-api
cd google-dns-api
Inside your project directory, run the go mod init command to initialize a new Go module:
go mod init google-dns-api
Create a new file called main.go
and open it in your text editor. Add the following code:
package main
import (
"encoding/json"
"fmt"
"net/http"
)
// Struct to represent the JSON response
type DNSResponse struct {
Status int `json:"Status"`
Answer []struct {
Name string `json:"name"`
Type int `json:"type"`
TTL int `json:"TTL"`
Data string `json:"data"`
} `json:"Answer"`
}
func main() {
// Google DNS API URL
url := "https://dns.google/resolve?name=example.com&type=A"
// Make the HTTP request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error during request:", err)
return
}
defer resp.Body.Close()
// Decode JSON response
var dnsResp DNSResponse
if err := json.NewDecoder(resp.Body).Decode(&dnsResp); err != nil {
fmt.Println("Error decoding response:", err)
return
}
// Print results
for _, answer := range dnsResp.Answer {
fmt.Printf("Name: %s, Type: %d, TTL: %d, Data: %s\n", answer.Name, answer.Type, answer.TTL, answer.Data)
}
}
In this example, we are making a request for the A record of "example.com". The JSON response is decoded into a Go struct and printed to the console.
Code Details:
- Importing Packages: We import the necessary packages (
encoding/json
,fmt
, andnet/http
). - Defining the Struct: The
DNSResponse
struct represents the format of the JSON response. - Making the HTTP Request: We use
http.Get
to make a GET request to Google's DNS API service. - Decoding the Response: We use
json.NewDecoder
to decode the JSON response directly into the defined Go type. - Printing the Results: We iterate through the responses and print the DNS record details.
Conclusion
Making requests to Google DNS APIs in Go is relatively easy thanks to Go's net/http
library and its ability to handle JSON natively. This example can be extended to handle different types of DNS records, add more sophisticated error handling, or integrate this functionality into a larger application. With Go, the power and simplicity of making HTTP requests and handling JSON makes this kind of task straightforward and efficient.