forked from nathanielc/morgoth
/
api.go
59 lines (52 loc) · 1.29 KB
/
api.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 morgoth
import (
"fmt"
"github.com/nathanielc/morgoth/Godeps/_workspace/src/github.com/ant0ine/go-json-rest/rest"
"github.com/nathanielc/morgoth/Godeps/_workspace/src/github.com/golang/glog"
"net"
"net/http"
)
type APIServer struct {
app *App
port uint
listener net.Listener
handler rest.ResourceHandler
}
func NewAPIServer(app *App, port uint) *APIServer {
return &APIServer{
app: app,
port: port,
}
}
func (self *APIServer) Start() (err error) {
self.handler = rest.ResourceHandler{
EnableStatusService: true,
}
self.handler.SetRoutes(
&rest.Route{"GET", "/status", self.status},
&rest.Route{"GET", "/stats", self.stats},
)
self.listener, err = net.Listen("tcp", fmt.Sprintf(":%d", self.port))
if err != nil {
glog.Errorf("Error binding APIServer: %s", err)
return
}
go func() {
err = http.Serve(self.listener, &self.handler)
if err != nil {
glog.Errorf("Error while APIServer was running: %s", err)
}
}()
glog.V(1).Info("APIServer running")
return
}
func (self *APIServer) Stop() {
self.listener.Close()
}
func (self *APIServer) status(w rest.ResponseWriter, req *rest.Request) {
w.WriteJson(self.handler.GetStatus())
}
func (self *APIServer) stats(w rest.ResponseWriter, req *rest.Request) {
stats := self.app.Stats
w.WriteJson(stats)
}