| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"io" |
| 7 |
"log" |
| 8 |
"net/http" |
| 9 |
"os" |
| 10 |
"os/signal" |
| 11 |
"strconv" |
| 12 |
"sync" |
| 13 |
"syscall" |
| 14 |
"time" |
| 15 |
|
| 16 |
_ "net/http/pprof" |
| 17 |
|
| 18 |
"github.com/centrifugal/centrifuge" |
| 19 |
"nhooyr.io/websocket" |
| 20 |
) |
| 21 |
|
| 22 |
type clientMessage struct { |
| 23 |
Timestamp int64 `json:"timestamp"` |
| 24 |
Input string `json:"input"` |
| 25 |
} |
| 26 |
|
| 27 |
func handleLog(e centrifuge.LogEntry) { |
| 28 |
log.Printf("%s: %v", e.Message, e.Fields) |
| 29 |
} |
| 30 |
|
| 31 |
func authMiddleware(h http.Handler) http.Handler { |
| 32 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 33 |
ctx := r.Context() |
| 34 |
newCtx := centrifuge.SetCredentials(ctx, ¢rifuge.Credentials{ |
| 35 |
UserID: "42", |
| 36 |
ExpireAt: time.Now().Unix() + 60, |
| 37 |
Info: []byte(`{"name": "Alexander"}`), |
| 38 |
}) |
| 39 |
r = r.WithContext(newCtx) |
| 40 |
h.ServeHTTP(w, r) |
| 41 |
}) |
| 42 |
} |
| 43 |
|
| 44 |
func waitExitSignal(n *centrifuge.Node) { |
| 45 |
sigCh := make(chan os.Signal, 1) |
| 46 |
done := make(chan bool, 1) |
| 47 |
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) |
| 48 |
go func() { |
| 49 |
<-sigCh |
| 50 |
_ = n.Shutdown(context.Background()) |
| 51 |
done <- true |
| 52 |
}() |
| 53 |
<-done |
| 54 |
} |
| 55 |
|
| 56 |
func main() { |
| 57 |
cfg := centrifuge.DefaultConfig |
| 58 |
cfg.LogLevel = centrifuge.LogLevelInfo |
| 59 |
cfg.LogHandler = handleLog |
| 60 |
|
| 61 |
node, _ := centrifuge.New(cfg) |
| 62 |
|
| 63 |
node.OnConnecting(func(ctx context.Context, e centrifuge.ConnectEvent) (centrifuge.ConnectReply, error) { |
| 64 |
return centrifuge.ConnectReply{ |
| 65 |
Credentials: ¢rifuge.Credentials{ |
| 66 |
UserID: "", |
| 67 |
}, |
| 68 |
}, nil |
| 69 |
}) |
| 70 |
|
| 71 |
node.OnConnect(func(client *centrifuge.Client) { |
| 72 |
transport := client.Transport() |
| 73 |
log.Printf("user %s connected via %s with protocol: %s", client.UserID(), transport.Name(), transport.Protocol()) |
| 74 |
|
| 75 |
// Connect handler should not block, so start separate goroutine to |
| 76 |
// periodically send messages to client. |
| 77 |
go func() { |
| 78 |
for { |
| 79 |
select { |
| 80 |
case <-client.Context().Done(): |
| 81 |
return |
| 82 |
case <-time.After(5 * time.Second): |
| 83 |
err := client.Send([]byte(`{"time": "` + strconv.FormatInt(time.Now().Unix(), 10) + `"}`)) |
| 84 |
if err != nil { |
| 85 |
if err == io.EOF { |
| 86 |
return |
| 87 |
} |
| 88 |
log.Println(err.Error()) |
| 89 |
} |
| 90 |
} |
| 91 |
} |
| 92 |
}() |
| 93 |
|
| 94 |
client.OnRefresh(func(e centrifuge.RefreshEvent, cb centrifuge.RefreshCallback) { |
| 95 |
log.Printf("user %s connection is going to expire, refreshing", client.UserID()) |
| 96 |
cb(centrifuge.RefreshReply{ |
| 97 |
ExpireAt: time.Now().Unix() + 60, |
| 98 |
}, nil) |
| 99 |
}) |
| 100 |
|
| 101 |
client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) { |
| 102 |
log.Printf("user %s subscribes on %s", client.UserID(), e.Channel) |
| 103 |
cb(centrifuge.SubscribeReply{ |
| 104 |
Options: centrifuge.SubscribeOptions{ |
| 105 |
ExpireAt: time.Now().Unix() + 60, |
| 106 |
}, |
| 107 |
}, nil) |
| 108 |
}) |
| 109 |
|
| 110 |
client.OnSubRefresh(func(e centrifuge.SubRefreshEvent, cb centrifuge.SubRefreshCallback) { |
| 111 |
log.Printf("user %s subscription on channel %s is going to expire, refreshing", client.UserID(), e.Channel) |
| 112 |
cb(centrifuge.SubRefreshReply{ |
| 113 |
ExpireAt: time.Now().Unix() + 60, |
| 114 |
}, nil) |
| 115 |
}) |
| 116 |
|
| 117 |
client.OnUnsubscribe(func(e centrifuge.UnsubscribeEvent) { |
| 118 |
log.Printf("user %s unsubscribed from %s", client.UserID(), e.Channel) |
| 119 |
}) |
| 120 |
|
| 121 |
client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) { |
| 122 |
log.Printf("user %s publishes into channel %s: %s", client.UserID(), e.Channel, string(e.Data)) |
| 123 |
var msg clientMessage |
| 124 |
err := json.Unmarshal(e.Data, &msg) |
| 125 |
if err != nil { |
| 126 |
cb(centrifuge.PublishReply{}, centrifuge.ErrorBadRequest) |
| 127 |
return |
| 128 |
} |
| 129 |
cb(centrifuge.PublishReply{}, nil) |
| 130 |
}) |
| 131 |
|
| 132 |
client.OnRPC(func(e centrifuge.RPCEvent, cb centrifuge.RPCCallback) { |
| 133 |
log.Printf("RPC from user: %s, data: %s", client.UserID(), string(e.Data)) |
| 134 |
cb(centrifuge.RPCReply{ |
| 135 |
Data: []byte(`{"year": "2020"}`), |
| 136 |
}, nil) |
| 137 |
}) |
| 138 |
|
| 139 |
client.OnMessage(func(e centrifuge.MessageEvent) { |
| 140 |
log.Printf("Message from user: %s, data: %s", client.UserID(), string(e.Data)) |
| 141 |
}) |
| 142 |
|
| 143 |
client.OnDisconnect(func(e centrifuge.DisconnectEvent) { |
| 144 |
log.Printf("user %s disconnected, disconnect: %s", client.UserID(), e.Disconnect) |
| 145 |
}) |
| 146 |
}) |
| 147 |
|
| 148 |
if err := node.Run(); err != nil { |
| 149 |
log.Fatal(err) |
| 150 |
} |
| 151 |
|
| 152 |
websocketHandler := newWebsocketHandler(node) |
| 153 |
http.Handle("/connection/websocket", authMiddleware(websocketHandler)) |
| 154 |
http.Handle("/", http.FileServer(http.Dir("./"))) |
| 155 |
|
| 156 |
go func() { |
| 157 |
if err := http.ListenAndServe(":8000", nil); err != nil { |
| 158 |
log.Fatal(err) |
| 159 |
} |
| 160 |
}() |
| 161 |
|
| 162 |
waitExitSignal(node) |
| 163 |
log.Println("bye!") |
| 164 |
} |
| 165 |
|
| 166 |
type customWebsocketHandler struct { |
| 167 |
node *centrifuge.Node |
| 168 |
} |
| 169 |
|
| 170 |
func newWebsocketHandler(node *centrifuge.Node) http.Handler { |
| 171 |
return &customWebsocketHandler{node} |
| 172 |
} |
| 173 |
|
| 174 |
const websocketTransportName = "websocket" |
| 175 |
|
| 176 |
type customWebsocketTransport struct { |
| 177 |
mu sync.RWMutex |
| 178 |
closed bool |
| 179 |
closeCh chan struct{} |
| 180 |
|
| 181 |
conn *websocket.Conn |
| 182 |
protoType centrifuge.ProtocolType |
| 183 |
request *http.Request |
| 184 |
} |
| 185 |
|
| 186 |
func newWebsocketTransport(conn *websocket.Conn, protoType centrifuge.ProtocolType) *customWebsocketTransport { |
| 187 |
return &customWebsocketTransport{ |
| 188 |
conn: conn, |
| 189 |
protoType: protoType, |
| 190 |
closeCh: make(chan struct{}), |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
// Name implementation. |
| 195 |
func (t *customWebsocketTransport) Name() string { |
| 196 |
return websocketTransportName |
| 197 |
} |
| 198 |
|
| 199 |
// Protocol implementation. |
| 200 |
func (t *customWebsocketTransport) Protocol() centrifuge.ProtocolType { |
| 201 |
return t.protoType |
| 202 |
} |
| 203 |
|
| 204 |
// Encoding implementation. |
| 205 |
func (t *customWebsocketTransport) Encoding() centrifuge.EncodingType { |
| 206 |
return centrifuge.EncodingTypeJSON |
| 207 |
} |
| 208 |
|
| 209 |
func (t *customWebsocketTransport) Write(data []byte) error { |
| 210 |
select { |
| 211 |
case <-t.closeCh: |
| 212 |
return nil |
| 213 |
default: |
| 214 |
var messageType = websocket.MessageText |
| 215 |
if t.Protocol() == centrifuge.ProtocolTypeProtobuf { |
| 216 |
messageType = websocket.MessageBinary |
| 217 |
} |
| 218 |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 219 |
defer cancel() |
| 220 |
err := t.conn.Write(ctx, messageType, data) |
| 221 |
if err != nil { |
| 222 |
return err |
| 223 |
} |
| 224 |
return nil |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
// Close implementation. |
| 229 |
func (t *customWebsocketTransport) Close(disconnect *centrifuge.Disconnect) error { |
| 230 |
t.mu.Lock() |
| 231 |
if t.closed { |
| 232 |
t.mu.Unlock() |
| 233 |
return nil |
| 234 |
} |
| 235 |
t.closed = true |
| 236 |
close(t.closeCh) |
| 237 |
t.mu.Unlock() |
| 238 |
|
| 239 |
if disconnect != nil { |
| 240 |
return t.conn.Close(websocket.StatusCode(disconnect.Code), disconnect.CloseText()) |
| 241 |
} |
| 242 |
return t.conn.Close(websocket.StatusNormalClosure, "") |
| 243 |
} |
| 244 |
|
| 245 |
func (s *customWebsocketHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { |
| 246 |
|
| 247 |
conn, err := websocket.Accept(rw, r, &websocket.AcceptOptions{}) |
| 248 |
if err != nil { |
| 249 |
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "websocket upgrade error", map[string]interface{}{"error": err.Error()})) |
| 250 |
return |
| 251 |
} |
| 252 |
|
| 253 |
var protoType = centrifuge.ProtocolTypeJSON |
| 254 |
if r.URL.Query().Get("format") == "protobuf" { |
| 255 |
protoType = centrifuge.ProtocolTypeProtobuf |
| 256 |
} |
| 257 |
|
| 258 |
transport := newWebsocketTransport(conn, protoType) |
| 259 |
|
| 260 |
select { |
| 261 |
case <-s.node.NotifyShutdown(): |
| 262 |
_ = transport.Close(centrifuge.DisconnectShutdown) |
| 263 |
return |
| 264 |
default: |
| 265 |
} |
| 266 |
|
| 267 |
c, closeFn, err := centrifuge.NewClient(r.Context(), s.node, transport) |
| 268 |
if err != nil { |
| 269 |
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error creating client", map[string]interface{}{"transport": websocketTransportName})) |
| 270 |
return |
| 271 |
} |
| 272 |
defer func() { _ = closeFn() }() |
| 273 |
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "client connection established", map[string]interface{}{"client": c.ID(), "transport": websocketTransportName})) |
| 274 |
defer func(started time.Time) { |
| 275 |
s.node.Log(centrifuge.NewLogEntry(centrifuge.LogLevelDebug, "client connection completed", map[string]interface{}{"client": c.ID(), "transport": websocketTransportName, "duration": time.Since(started)})) |
| 276 |
}(time.Now()) |
| 277 |
|
| 278 |
for { |
| 279 |
_, data, err := conn.Read(context.Background()) |
| 280 |
if err != nil { |
| 281 |
return |
| 282 |
} |
| 283 |
ok := c.Handle(data) |
| 284 |
if !ok { |
| 285 |
return |
| 286 |
} |
| 287 |
} |
| 288 |
} |