Skip to content

Instantly share code, notes, and snippets.

@haginara
Created February 27, 2020 23:59
Show Gist options
  • Save haginara/0c56f6fff69d4594957d51404c67ae27 to your computer and use it in GitHub Desktop.
Save haginara/0c56f6fff69d4594957d51404c67ae27 to your computer and use it in GitHub Desktop.
Example code to query dns to cloudflare-dns.com
package main
import (
"encoding/json"
"log"
"fmt"
"net/http"
)
type DNSQuestion struct {
Name string `json:"name"`
Type int `json:"type"`
}
type DNSAnswer struct {
Name string `json:"name"`
Type int `json:"type"`
TTL int `json:"TTL"`
Data string `json:"data"`
}
type DNSResponse struct {
Status int `json:"Status"`
TC bool `json:"TC"`
RD bool `json:"RD"`
RA bool `json:"RA"`
AD bool `json:"AD"`
CD bool `json:"CD"`
Question []DNSQuestion `json"Question"`
Answer []DNSAnswer `json"Question"`
}
func Lookup(name, qtype string) (*DNSResponse, error) {
url := fmt.Sprintf(
"https://cloudflare-dns.com/dns-query?name=%s&type=%s",
name,
qtype,
)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/dns-json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
}
var response DNSResponse
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return nil, err
}
defer res.Body.Close()
return &response, nil
}
func main() {
response, err := Lookup("www.google.com", "A")
if err != nil {
log.Fatalln(err)
}
log.Printf("Status: %d, Name: %s, LenOfAnswers: %d", response.Status, response.Question[0].Name, len(response.Answer))
for _, answer := range response.Answer {
log.Printf("Data: %s", answer.Data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment