github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/api/websocket.go (about)

     1  package api
     2  
     3  import (
     4  	"net/http"
     5  	"time"
     6  
     7  	log "github.com/sirupsen/logrus"
     8  
     9  	"github.com/bytom/bytom/net/websocket"
    10  )
    11  
    12  // timeZeroVal is simply the zero value for a time.Time and is used to avoid
    13  // creating multiple instances.
    14  var timeZeroVal time.Time
    15  
    16  // WebsocketHandler handles connections and requests from websocket client
    17  func (a *API) websocketHandler(w http.ResponseWriter, r *http.Request) {
    18  	log.WithField("remoteAddress", r.RemoteAddr).Info("New websocket client")
    19  
    20  	client, err := websocket.NewWebsocketClient(w, r, a.notificationMgr)
    21  	if err != nil {
    22  		log.WithField("error", err).Error("Failed to new websocket client")
    23  		http.Error(w, "400 Bad Request.", http.StatusBadRequest)
    24  		return
    25  	}
    26  
    27  	a.notificationMgr.AddClient(client)
    28  	client.Start()
    29  	client.WaitForShutdown()
    30  	a.notificationMgr.RemoveClient(client)
    31  	log.WithField("address", r.RemoteAddr).Infoln("Disconnected websocket client")
    32  }