-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
59 lines (52 loc) · 1.19 KB
/
handlers.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
package main
import (
"io"
"log"
"net"
"net/http"
"strings"
)
type handler func(w http.ResponseWriter, r *http.Request)
func GetOnly(h handler) handler {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
h(w, r)
return
}
http.Error(w, "get only", http.StatusMethodNotAllowed)
}
}
func PingHandler(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
io.WriteString(rw, "pong")
}
func ResolveHandler(rw http.ResponseWriter, req *http.Request) {
dn := req.FormValue("dn")
if dn == "" {
log.Printf("invalid req: %v", req.URL)
http.Error(rw, "Invalid parameter", http.StatusBadRequest)
return
}
resolver := GetResolver()
if ip, err := resolver.GetIp(dn); err == nil {
log.Printf("dn: %v, ip: %v", dn, ip)
rw.WriteHeader(http.StatusOK)
io.WriteString(rw, ip)
return
}
if ips, err := net.LookupIP(dn); err == nil {
resp := ips[0].String()
if len(ips) > 1 {
strs := make([]string, len(ips))
for i, v := range ips {
strs[i] = v.String()
}
resp = strings.Join(strs, ";")
}
log.Printf("dn: %v, ip: %v", dn, resp)
rw.WriteHeader(http.StatusOK)
io.WriteString(rw, resp)
return
}
http.NotFound(rw, req)
}