|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "io" |
| 7 | + "io/ioutil" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | + "sync" |
| 11 | + "time" |
| 12 | + |
| 13 | + "nhooyr.io/websocket" |
| 14 | +) |
| 15 | + |
| 16 | +// chatServer enables broadcasting to a set of subscribers. |
| 17 | +type chatServer struct { |
| 18 | + subscribersMu sync.RWMutex |
| 19 | + subscribers map[chan<- []byte]struct{} |
| 20 | +} |
| 21 | + |
| 22 | +// subscribeHandler accepts the WebSocket connection and then subscribes |
| 23 | +// it to all future messages. |
| 24 | +func (cs *chatServer) subscribeHandler(w http.ResponseWriter, r *http.Request) { |
| 25 | + c, err := websocket.Accept(w, r, nil) |
| 26 | + if err != nil { |
| 27 | + log.Print(err) |
| 28 | + return |
| 29 | + } |
| 30 | + defer c.Close(websocket.StatusInternalError, "") |
| 31 | + |
| 32 | + err = cs.subscribe(r.Context(), c) |
| 33 | + if errors.Is(err, context.Canceled) { |
| 34 | + return |
| 35 | + } |
| 36 | + if websocket.CloseStatus(err) == websocket.StatusNormalClosure || |
| 37 | + websocket.CloseStatus(err) == websocket.StatusGoingAway { |
| 38 | + return |
| 39 | + } |
| 40 | + if err != nil { |
| 41 | + log.Print(err) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// publishHandler reads the request body with a limit of 8192 bytes and then publishes |
| 46 | +// the received message. |
| 47 | +func (cs *chatServer) publishHandler(w http.ResponseWriter, r *http.Request) { |
| 48 | + if r.Method != "POST" { |
| 49 | + http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) |
| 50 | + return |
| 51 | + } |
| 52 | + body := io.LimitReader(r.Body, 8192) |
| 53 | + msg, err := ioutil.ReadAll(body) |
| 54 | + if err != nil { |
| 55 | + http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge) |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + cs.publish(msg) |
| 60 | +} |
| 61 | + |
| 62 | +// subscribe subscribes the given WebSocket to all broadcast messages. |
| 63 | +// It creates a msgs chan with a buffer of 16 to give some room to slower |
| 64 | +// connections and then registers it. It then listens for all messages |
| 65 | +// and writes them to the WebSocket. If the context is cancelled or |
| 66 | +// an error occurs, it returns and deletes the subscription. |
| 67 | +// |
| 68 | +// It uses CloseRead to keep reading from the connection to process control |
| 69 | +// messages and cancel the context if the connection drops. |
| 70 | +func (cs *chatServer) subscribe(ctx context.Context, c *websocket.Conn) error { |
| 71 | + ctx = c.CloseRead(ctx) |
| 72 | + |
| 73 | + msgs := make(chan []byte, 16) |
| 74 | + cs.addSubscriber(msgs) |
| 75 | + defer cs.deleteSubscriber(msgs) |
| 76 | + |
| 77 | + for { |
| 78 | + select { |
| 79 | + case msg := <-msgs: |
| 80 | + err := writeTimeout(ctx, time.Second*5, c, msg) |
| 81 | + if err != nil { |
| 82 | + return err |
| 83 | + } |
| 84 | + case <-ctx.Done(): |
| 85 | + return ctx.Err() |
| 86 | + } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +// publish publishes the msg to all subscribers. |
| 91 | +// It never blocks and so messages to slow subscribers |
| 92 | +// are dropped. |
| 93 | +func (cs *chatServer) publish(msg []byte) { |
| 94 | + cs.subscribersMu.RLock() |
| 95 | + defer cs.subscribersMu.RUnlock() |
| 96 | + |
| 97 | + for c := range cs.subscribers { |
| 98 | + select { |
| 99 | + case c <- msg: |
| 100 | + default: |
| 101 | + } |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +// addSubscriber registers a subscriber with a channel |
| 106 | +// on which to send messages. |
| 107 | +func (cs *chatServer) addSubscriber(msgs chan<- []byte) { |
| 108 | + cs.subscribersMu.Lock() |
| 109 | + if cs.subscribers == nil { |
| 110 | + cs.subscribers = make(map[chan<- []byte]struct{}) |
| 111 | + } |
| 112 | + cs.subscribers[msgs] = struct{}{} |
| 113 | + cs.subscribersMu.Unlock() |
| 114 | +} |
| 115 | + |
| 116 | +// deleteSubscriber deletes the subscriber with the given msgs channel. |
| 117 | +func (cs *chatServer) deleteSubscriber(msgs chan []byte) { |
| 118 | + cs.subscribersMu.Lock() |
| 119 | + delete(cs.subscribers, msgs) |
| 120 | + cs.subscribersMu.Unlock() |
| 121 | +} |
| 122 | + |
| 123 | +func writeTimeout(ctx context.Context, timeout time.Duration, c *websocket.Conn, msg []byte) error { |
| 124 | + ctx, cancel := context.WithTimeout(ctx, timeout) |
| 125 | + defer cancel() |
| 126 | + |
| 127 | + return c.Write(ctx, websocket.MessageText, msg) |
| 128 | +} |
0 commit comments