8460: Scaffold for websocket server.
[arvados.git] / services / ws / router.go
1 package main
2
3 import (
4         "io"
5         "log"
6         "net/http"
7         "sync"
8
9         "golang.org/x/net/websocket"
10 )
11
12 type router struct {
13         EventSource <-chan event
14         mux         *http.ServeMux
15         setupOnce   sync.Once
16 }
17
18 func (rtr *router) setup() {
19         rtr.mux = http.NewServeMux()
20         rtr.mux.Handle("/websocket", makeServer(handlerV0))
21         rtr.mux.Handle("/arvados/v1/events.ws", makeServer(handlerV1))
22 }
23
24 func makeServer(handler func(io.ReadWriter)) websocket.Server {
25         return websocket.Server{
26                 Handshake: func(c *websocket.Config, r *http.Request) error {
27                         return nil
28                 },
29                 Handler: websocket.Handler(func(ws *websocket.Conn) {
30                         log.Printf("socket request: %+v", ws.Request())
31                         handler(ws)
32                         ws.Close()
33                         log.Printf("socket disconnect: %+v", ws.Request().RemoteAddr)
34                 }),
35         }
36 }
37
38 func (rtr *router) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
39         rtr.setupOnce.Do(rtr.setup)
40         rtr.mux.ServeHTTP(resp, req)
41 }