Serve accepts incoming connections and serve each.
()
| 22 | |
| 23 | // Serve accepts incoming connections and serve each. |
| 24 | func (ws *WebsocketServer) Serve() error { |
| 25 | var ( |
| 26 | mux = http.NewServeMux() |
| 27 | upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} |
| 28 | handler = ws.RPCHandler |
| 29 | ) |
| 30 | |
| 31 | if handler == nil { |
| 32 | handler = defaultHandler |
| 33 | } |
| 34 | |
| 35 | mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { |
| 36 | conn, err := upgrader.Upgrade(rw, r, nil) |
| 37 | if err != nil { |
| 38 | log.WithError(err).Error("jsonrpc: upgrade http connection to websocket failed") |
| 39 | http.Error(rw, errors.WithMessage(err, "could not upgrade to websocket").Error(), http.StatusBadRequest) |
| 40 | return |
| 41 | } |
| 42 | defer conn.Close() |
| 43 | |
| 44 | // TODO: add metric for the connections |
| 45 | <-jsonrpc2.NewConn( |
| 46 | context.Background(), |
| 47 | wsstream.NewObjectStream(conn), |
| 48 | handler, |
| 49 | ).DisconnectNotify() |
| 50 | }) |
| 51 | |
| 52 | addr := ws.Addr |
| 53 | listener, err := net.Listen("tcp", addr) |
| 54 | if err != nil { |
| 55 | return errors.Wrapf(err, "couldn't bind to address %q", addr) |
| 56 | } |
| 57 | |
| 58 | ws.Handler = mux |
| 59 | return ws.Server.Serve(listener) |
| 60 | } |
| 61 | |
| 62 | // Stop stops the server and returns a channel indicating server is stopped. |
| 63 | func (ws *WebsocketServer) Stop() { |