-
Notifications
You must be signed in to change notification settings - Fork 35
/
http.go
103 lines (88 loc) · 2.12 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
92
93
94
95
96
97
98
99
100
101
102
103
package beehive
import (
"bytes"
"encoding/gob"
"encoding/json"
"net/http"
"github.com/kandoo/beehive/Godeps/_workspace/src/github.com/gorilla/mux"
)
// state is served as json while other endpoints serve gob. The reason is that
// state should be human readable.
const (
serverV1StatePath = "/api/v1/state"
serverV1BeesPath = "/api/v1/bees"
)
func buildURL(scheme, addr, path string) string {
var buffer bytes.Buffer
buffer.WriteString(scheme)
buffer.WriteString("://")
buffer.WriteString(addr)
buffer.WriteString(path)
return buffer.String()
}
// server is the HTTP server that act as the remote endpoint for Beehive.
type httpServer struct {
http.Server
hive *hive
router *mux.Router
}
// newServer creates a new server for the hive.
func newServer(h *hive) *httpServer {
r := mux.NewRouter()
s := &httpServer{
Server: http.Server{
Addr: h.config.Addr,
Handler: r,
},
router: r,
hive: h,
}
v1 := v1Handler{srv: s}
v1.install(r)
w := webHandler{}
w.install(r)
if h.config.Pprof {
p := pprofHandler{}
p.install(r)
}
return s
}
// Provides the net/http interface for the server.
func (s *httpServer) HandleFunc(p string,
h func(http.ResponseWriter, *http.Request)) {
s.router.HandleFunc(p, h)
}
type v1Handler struct {
srv *httpServer
}
func (h *v1Handler) install(r *mux.Router) {
r.HandleFunc(serverV1StatePath, h.handleHiveState)
r.HandleFunc(serverV1BeesPath, h.handleBees)
}
func (h *v1Handler) handleHiveState(w http.ResponseWriter, r *http.Request) {
s := HiveState{
ID: h.srv.hive.ID(),
Addr: h.srv.hive.config.Addr,
Peers: h.srv.hive.registry.hives(),
}
j, err := json.Marshal(s)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
func (h *v1Handler) handleBees(w http.ResponseWriter, r *http.Request) {
bees := h.srv.hive.registry.bees()
j, err := json.Marshal(bees)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(j)
}
func init() {
gob.Register(HiveState{})
}