62 lines
1.1 KiB
Go
62 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"nhooyr.io/websocket"
|
|
)
|
|
|
|
type logWebsocket struct {
|
|
}
|
|
|
|
func (l logWebsocket) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
parts := strings.Split(r.URL.Path[1:], "/")
|
|
run := runss.getRun(parts[2])
|
|
if run == nil {
|
|
http.Error(w, "log not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
c, err := websocket.Accept(w, r, nil)
|
|
if err != nil {
|
|
http.Error(w, "this a websocket path", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defer c.Close(websocket.StatusInternalError, "the sky is falling")
|
|
|
|
ch := make(chan *[]byte, 1000)
|
|
err = run.addWriter(conn{ch: ch})
|
|
if err != nil {
|
|
log.Println("addWriter", err)
|
|
http.Error(w, "error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
for payload := range ch {
|
|
if payload == nil {
|
|
break
|
|
} else {
|
|
err = c.Write(context.Background(), websocket.MessageBinary, *payload)
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
c.Close(websocket.StatusNormalClosure, "")
|
|
}
|
|
|
|
type conn struct {
|
|
ch chan *[]byte
|
|
}
|
|
|
|
func (c conn) Write(payload []byte) (n int, err error) {
|
|
c.ch <- &payload
|
|
return len(payload), nil
|
|
}
|
|
func (c conn) Close() error {
|
|
c.ch <- nil
|
|
return nil
|
|
}
|