/ pkg / web / websocket_logger.go
websocket_logger.go
 1  package web
 2  
 3  import (
 4  	"fmt"
 5  
 6  	dogeboxd "github.com/dogeorg/dogeboxd/pkg"
 7  	"golang.org/x/net/websocket"
 8  )
 9  
10  func GetLogHandler(PupID string, dbx dogeboxd.Dogeboxd) (*websocket.Server, error) {
11  	cancel, logChan, err := dbx.GetLogChannel(PupID)
12  	if err != nil {
13  		fmt.Println("ERR", err)
14  		return nil, err
15  	}
16  	config := &websocket.Config{
17  		Origin: nil,
18  	}
19  
20  	stop := make(chan bool)  // WSCONN stop channel
21  	start := make(chan bool) // tell the goroutine pump to start
22  	conn := WSCONN{Stop: stop}
23  
24  	h := websocket.Server{
25  		Handler: func(ws *websocket.Conn) {
26  			conn.WS = ws
27  			start <- true
28  			<-stop   // hold the connection until stopper closes
29  			cancel() // tell the log producer to stop
30  		},
31  		Config: *config,
32  	}
33  
34  	// create a pump that broadcasts logs
35  	go func() {
36  		<-start
37  	out:
38  		for {
39  			select {
40  			case <-stop:
41  				break out
42  			case v, ok := <-logChan:
43  				if !ok {
44  					conn.Close()
45  					break
46  				}
47  				err := websocket.JSON.Send(conn.WS, v)
48  				if err != nil {
49  					fmt.Println("ERR sending, closing websocket", err)
50  					conn.Close()
51  				}
52  			}
53  		}
54  	}()
55  
56  	return &h, nil
57  }