|
|
@@ -6,7 +6,6 @@ import (
|
|
|
"encoding/json"
|
|
|
"errors"
|
|
|
"fmt"
|
|
|
- "github.com/gorilla/websocket"
|
|
|
"io"
|
|
|
"log"
|
|
|
"net/http"
|
|
|
@@ -18,11 +17,11 @@ import (
|
|
|
|
|
|
type Server struct {
|
|
|
topics map[string]*topic
|
|
|
- mu sync.Mutex
|
|
|
+ mu sync.Mutex
|
|
|
}
|
|
|
|
|
|
type message struct {
|
|
|
- Time int64 `json:"time"`
|
|
|
+ Time int64 `json:"time"`
|
|
|
Message string `json:"message"`
|
|
|
}
|
|
|
|
|
|
@@ -31,14 +30,9 @@ const (
|
|
|
)
|
|
|
|
|
|
var (
|
|
|
- topicRegex = regexp.MustCompile(`^/[^/]+$`)
|
|
|
- jsonRegex = regexp.MustCompile(`^/[^/]+/json$`)
|
|
|
- sseRegex = regexp.MustCompile(`^/[^/]+/sse$`)
|
|
|
- wsRegex = regexp.MustCompile(`^/[^/]+/ws$`)
|
|
|
- wsUpgrader = websocket.Upgrader{
|
|
|
- ReadBufferSize: messageLimit,
|
|
|
- WriteBufferSize: messageLimit,
|
|
|
- }
|
|
|
+ topicRegex = regexp.MustCompile(`^/[^/]+$`)
|
|
|
+ jsonRegex = regexp.MustCompile(`^/[^/]+/json$`)
|
|
|
+ sseRegex = regexp.MustCompile(`^/[^/]+/sse$`)
|
|
|
|
|
|
//go:embed "index.html"
|
|
|
indexSource string
|
|
|
@@ -51,26 +45,32 @@ func New() *Server {
|
|
|
}
|
|
|
|
|
|
func (s *Server) Run() error {
|
|
|
- go func() {
|
|
|
- for {
|
|
|
- time.Sleep(5 * time.Second)
|
|
|
- s.mu.Lock()
|
|
|
- log.Printf("topics: %d", len(s.topics))
|
|
|
- for _, t := range s.topics {
|
|
|
- t.mu.Lock()
|
|
|
- log.Printf("- %s: %d subscriber(s), %d message(s) sent, last active = %s",
|
|
|
- t.id, len(t.subscribers), t.messages, t.last.String())
|
|
|
- t.mu.Unlock()
|
|
|
- }
|
|
|
- // TODO kill dead topics
|
|
|
- s.mu.Unlock()
|
|
|
- }
|
|
|
- }()
|
|
|
+ go s.runMonitor()
|
|
|
+ return s.listenAndServe()
|
|
|
+}
|
|
|
+
|
|
|
+func (s *Server) listenAndServe() error {
|
|
|
log.Printf("Listening on :9997")
|
|
|
http.HandleFunc("/", s.handle)
|
|
|
return http.ListenAndServe(":9997", nil)
|
|
|
}
|
|
|
|
|
|
+func (s *Server) runMonitor() {
|
|
|
+ for {
|
|
|
+ time.Sleep(5 * time.Second)
|
|
|
+ s.mu.Lock()
|
|
|
+ log.Printf("topics: %d", len(s.topics))
|
|
|
+ for _, t := range s.topics {
|
|
|
+ t.mu.Lock()
|
|
|
+ log.Printf("- %s: %d subscriber(s), %d message(s) sent, last active = %s",
|
|
|
+ t.id, len(t.subscribers), t.messages, t.last.String())
|
|
|
+ t.mu.Unlock()
|
|
|
+ }
|
|
|
+ // TODO kill dead topics
|
|
|
+ s.mu.Unlock()
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
|
|
|
if err := s.handleInternal(w, r); err != nil {
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
@@ -81,8 +81,6 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
|
|
|
func (s *Server) handleInternal(w http.ResponseWriter, r *http.Request) error {
|
|
|
if r.Method == http.MethodGet && r.URL.Path == "/" {
|
|
|
return s.handleHome(w, r)
|
|
|
- } else if r.Method == http.MethodGet && wsRegex.MatchString(r.URL.Path) {
|
|
|
- return s.handleSubscribeWS(w, r)
|
|
|
} else if r.Method == http.MethodGet && jsonRegex.MatchString(r.URL.Path) {
|
|
|
return s.handleSubscribeJSON(w, r)
|
|
|
} else if r.Method == http.MethodGet && sseRegex.MatchString(r.URL.Path) {
|
|
|
@@ -118,7 +116,7 @@ func (s *Server) handlePublishHTTP(w http.ResponseWriter, r *http.Request) error
|
|
|
|
|
|
func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request) error {
|
|
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/json")) // Hack
|
|
|
- subscriberID := t.Subscribe(func (msg *message) error {
|
|
|
+ subscriberID := t.Subscribe(func(msg *message) error {
|
|
|
if err := json.NewEncoder(w).Encode(&msg); err != nil {
|
|
|
return err
|
|
|
}
|
|
|
@@ -137,12 +135,12 @@ func (s *Server) handleSubscribeJSON(w http.ResponseWriter, r *http.Request) err
|
|
|
|
|
|
func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request) error {
|
|
|
t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/sse")) // Hack
|
|
|
- subscriberID := t.Subscribe(func (msg *message) error {
|
|
|
+ subscriberID := t.Subscribe(func(msg *message) error {
|
|
|
var buf bytes.Buffer
|
|
|
if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
|
|
|
return err
|
|
|
}
|
|
|
- m := fmt.Sprintf("data: %s\n\n", buf.String())
|
|
|
+ m := fmt.Sprintf("data: %s\n", buf.String())
|
|
|
if _, err := io.WriteString(w, m); err != nil {
|
|
|
return err
|
|
|
}
|
|
|
@@ -154,6 +152,12 @@ func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request) erro
|
|
|
defer t.Unsubscribe(subscriberID)
|
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
+ if _, err := io.WriteString(w, "event: open\n\n"); err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ if fl, ok := w.(http.Flusher); ok {
|
|
|
+ fl.Flush()
|
|
|
+ }
|
|
|
select {
|
|
|
case <-t.ctx.Done():
|
|
|
case <-r.Context().Done():
|
|
|
@@ -161,40 +165,6 @@ func (s *Server) handleSubscribeSSE(w http.ResponseWriter, r *http.Request) erro
|
|
|
return nil
|
|
|
}
|
|
|
|
|
|
-func (s *Server) handleSubscribeWS(w http.ResponseWriter, r *http.Request) error {
|
|
|
- conn, err := wsUpgrader.Upgrade(w, r, nil)
|
|
|
- if err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- t := s.createTopic(strings.TrimSuffix(r.URL.Path[1:], "/ws")) // Hack
|
|
|
- t.Subscribe(func (msg *message) error {
|
|
|
- var buf bytes.Buffer
|
|
|
- if err := json.NewEncoder(&buf).Encode(&msg); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- defer conn.Close()
|
|
|
- /*conn.SetWriteDeadline(time.Now().Add(writeWait))
|
|
|
- if !ok {
|
|
|
- // The hub closed the channel.
|
|
|
- c.conn.WriteMessage(websocket.CloseMessage, []byte{})
|
|
|
- return
|
|
|
- }*/
|
|
|
-
|
|
|
- w, err := conn.NextWriter(websocket.TextMessage)
|
|
|
- if err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- if _, err := w.Write([]byte(msg.Message)); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- if err := w.Close(); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- return nil
|
|
|
- })
|
|
|
- return nil
|
|
|
-}
|
|
|
-
|
|
|
func (s *Server) createTopic(id string) *topic {
|
|
|
s.mu.Lock()
|
|
|
defer s.mu.Unlock()
|