forked from raystack/raccoon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
73 lines (60 loc) · 1.86 KB
/
Copy pathservice.go
File metadata and controls
73 lines (60 loc) · 1.86 KB
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
package rest
import (
"context"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/goto/raccoon/collection"
"github.com/goto/raccoon/config"
"github.com/goto/raccoon/metrics"
"github.com/goto/raccoon/services/rest/websocket"
"github.com/goto/raccoon/services/rest/websocket/connection"
)
type Service struct {
Collector collection.Collector
s *http.Server
}
func NewRestService(c collection.Collector) *Service {
pingChannel := make(chan connection.Conn, config.ServerWs.ServerMaxConn)
wh := websocket.NewHandler(pingChannel, c)
go websocket.Pinger(pingChannel, config.ServerWs.PingerSize, config.ServerWs.PingInterval, config.ServerWs.WriteWaitInterval)
go reportConnectionMetrics(*wh.Table())
go websocket.AckHandler(websocket.AckChan)
restHandler := NewHandler(c)
router := mux.NewRouter()
router.Path("/ping").HandlerFunc(pingHandler).Methods(http.MethodGet)
subRouter := router.PathPrefix("/api/v1").Subrouter()
subRouter.HandleFunc("/events", wh.HandlerWSEvents).Methods(http.MethodGet).Name("events")
subRouter.HandleFunc("/events", restHandler.RESTAPIHandler).Methods(http.MethodPost).Name("events")
server := &http.Server{
Handler: router,
Addr: ":" + config.ServerWs.AppPort,
}
return &Service{
s: server,
Collector: c,
}
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("pong"))
}
func reportConnectionMetrics(conn connection.Table) {
t := time.Tick(config.MetricStatsd.FlushPeriodMs)
for {
<-t
conn.RangeConnectionPerGroup(func(k string, v int) {
metrics.Gauge("connections_count_current", v, fmt.Sprintf("conn_group=%s", k))
})
}
}
func (s *Service) Init(context.Context) error {
return s.s.ListenAndServe()
}
func (*Service) Name() string {
return "REST"
}
func (s *Service) Shutdown(ctx context.Context) error {
return s.s.Shutdown(ctx)
}