forked from CyCoreSystems/dispatchers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
69 lines (57 loc) · 1.61 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
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"strconv"
"strings"
)
func (s *dispatcherSets) startHTTP(ctx context.Context, addr string) {
http.HandleFunc("/check/", s.handleIPCheckRequest)
http.HandleFunc("/dispatcher/", s.handleListSetRequest)
http.HandleFunc("/dispatchers/", s.handleListSetRequest)
log.Fatalln(http.ListenAndServe(addr, nil))
}
// Check IP address for membership in a dispatcher set.
// URL: /check/<setID>/<ip>
func (s *dispatcherSets) handleIPCheckRequest(w http.ResponseWriter, r *http.Request) {
pieces := strings.Split(strings.TrimPrefix(r.URL.Path, "/check/"), "/")
if len(pieces) != 2 {
w.WriteHeader(http.StatusBadRequest)
return
}
setID, err := strconv.Atoi(pieces[0])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if s.validateSetMember(setID, pieces[1]) {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusNotFound)
}
// Return a given dispatcher set
// URL: /dispatcher/<setID>
func (s *dispatcherSets) handleListSetRequest(w http.ResponseWriter, r *http.Request) {
pieces := strings.Split(strings.TrimPrefix(r.URL.Path, "/dispatcher/"), "/")
if len(pieces) != 1 {
w.WriteHeader(http.StatusBadRequest)
return
}
setID, err := strconv.Atoi(pieces[0])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
selectedSet := s.getDispatcherSet(setID)
if selectedSet != nil {
w.Header().Add("Content-Type", "application/json")
if err = json.NewEncoder(w).Encode(selectedSet.Hosts()); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
return
}
w.WriteHeader(http.StatusNotFound)
}