forked from weaveworks/weave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
91 lines (75 loc) · 2.37 KB
/
http.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
package nameserver
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/miekg/dns"
"github.com/weaveworks/weave/common/docker"
"github.com/weaveworks/weave/net/address"
)
func (n *Nameserver) badRequest(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
n.infof("%v", err)
}
func (n *Nameserver) HandleHTTP(router *mux.Router, dockerCli *docker.Client) {
router.Methods("GET").Path("/domain").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, n.domain)
})
router.Methods("PUT").Path("/name/{container}/{ip}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
vars = mux.Vars(r)
container = vars["container"]
ipStr = vars["ip"]
hostname = dns.Fqdn(r.FormValue("fqdn"))
ip, err = address.ParseIP(ipStr)
)
if err != nil {
n.badRequest(w, err)
return
}
if !dns.IsSubDomain(n.domain, hostname) {
n.infof("Ignoring registration %s %s %s (not a subdomain of %s)", hostname, ipStr, container, n.domain)
return
}
n.AddEntry(hostname, container, n.ourName, ip)
if r.FormValue("check-alive") == "true" && dockerCli != nil && dockerCli.IsContainerNotRunning(container) {
n.infof("container '%s' is not running: removing", container)
n.Delete(hostname, container, ipStr, ip)
}
w.WriteHeader(204)
})
deleteHandler := func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hostname := r.FormValue("fqdn")
if hostname == "" {
hostname = "*"
} else {
hostname = dns.Fqdn(hostname)
}
container, ok := vars["container"]
if !ok {
container = "*"
}
ipStr, ok := vars["ip"]
ip, err := address.ParseIP(ipStr)
if ok && err != nil {
n.badRequest(w, err)
return
} else if !ok {
ipStr = "*"
}
n.Delete(hostname, container, ipStr, ip)
w.WriteHeader(204)
}
router.Methods("DELETE").Path("/name/{container}/{ip}").HandlerFunc(deleteHandler)
router.Methods("DELETE").Path("/name/{container}").HandlerFunc(deleteHandler)
router.Methods("DELETE").Path("/name").HandlerFunc(deleteHandler)
router.Methods("GET").Path("/name").Headers("Accept", "application/json").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n.RLock()
defer n.RUnlock()
if err := json.NewEncoder(w).Encode(n.entries); err != nil {
n.badRequest(w, fmt.Errorf("Error marshalling response: %v", err))
}
})
}