-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
103 lines (87 loc) · 2.14 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// DNSQuestion is a DNS question struct with Name and Q-Type
type DNSQuestion struct {
Name string `json:"name"`
Type uint16 `json:"type"`
}
// DNSAnswer is a DNS answer struct with Name, Q-Type, TTL and Data
type DNSAnswer struct {
Name string `json:"name"`
Type uint16 `json:"type"`
TTL int `json:"TTL"`
Data string `json:"data"`
}
// DNSResponse amalgamates Questions and Answers slices
type DNSResponse struct {
Questions []DNSQuestion `json:"Question"`
Answers []DNSAnswer `json:"Answer"`
}
// DNSError returns back any errors that may have been encountered
type DNSError struct {
Error string `json:"error"`
}
// Router is the HTTP router
type Router struct {
HTTPClient *http.Client
}
func newHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
}
}
// GetDNS returns a DNSResponse of Questions and Answers
func (ro Router) GetDNS(c *gin.Context) {
domain := c.Param("domain")
qType := c.Param("qtype")
dnsReq := fmt.Sprintf("%s?name=%s&type=%s", GoogleDNS, domain, qType)
log.Println("Requesting: ", dnsReq)
resp, err := ro.HTTPClient.Get(dnsReq)
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, DNSError{
Error: http.StatusText(http.StatusInternalServerError),
})
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, DNSError{
Error: http.StatusText(http.StatusInternalServerError),
})
return
}
dnsResp := DNSResponse{}
err = json.Unmarshal(body, &dnsResp)
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, DNSError{
Error: http.StatusText(http.StatusInternalServerError),
})
return
}
// return answer back
c.JSON(http.StatusOK, dnsResp)
}
func (ro Router) setupRouter() *gin.Engine {
r := gin.Default()
r.GET("/dns/:domain/:qtype", ro.GetDNS)
return r
}
func main() {
ro := Router{
HTTPClient: newHTTPClient(time.Second * 10),
}
r := ro.setupRouter()
r.Run() // listen and serve on 0.0.0.0:8080
}