package main import ( "bytes" "context" "encoding/binary" "errors" "io" "log" "net" "net/http" "os" "os/signal" "sync" "syscall" "time" ) // --------------------------------------------------------------------------- // Broadcaster — holds the latest frame and fans it out to all HTTP clients // --------------------------------------------------------------------------- type Broadcaster struct { mu sync.RWMutex frame []byte clients map[chan []byte]struct{} clientMu sync.Mutex } func NewBroadcaster() *Broadcaster { return &Broadcaster{ clients: make(map[chan []byte]struct{}), } } func (b *Broadcaster) Publish(frame []byte) { // Store latest frame for new clients joining mid-stream b.mu.Lock() b.frame = frame b.mu.Unlock() // Fan out to all connected clients b.clientMu.Lock() defer b.clientMu.Unlock() for ch := range b.clients { select { case ch <- frame: default: // Client is too slow — drop this frame rather than blocking } } } func (b *Broadcaster) Subscribe() (chan []byte, []byte) { ch := make(chan []byte, 4) // small buffer so slow clients drop frames, not block b.clientMu.Lock() b.clients[ch] = struct{}{} b.clientMu.Unlock() // Send the latest frame immediately so the client doesn't wait b.mu.RLock() latest := b.frame b.mu.RUnlock() return ch, latest } func (b *Broadcaster) Unsubscribe(ch chan []byte) { b.clientMu.Lock() delete(b.clients, ch) b.clientMu.Unlock() } // --------------------------------------------------------------------------- // Socket reader — reads length-prefixed MJPEG frames from a Unix socket // Python writes: [4-byte big-endian length][JPEG bytes] // --------------------------------------------------------------------------- func socketReader(sockPath string, b *Broadcaster) { for { conn, err := net.Dial("unix", sockPath) if err != nil { log.Printf("[socket] waiting for %s: %v", sockPath, err) time.Sleep(2 * time.Second) continue } log.Printf("[socket] connected to %s", sockPath) for { // Read 4-byte length prefix var length uint32 if err := binary.Read(conn, binary.BigEndian, &length); err != nil { log.Printf("[socket] read length error: %v", err) break } if length == 0 || length > 10*1024*1024 { log.Printf("[socket] invalid frame length %d, reconnecting", length) break } // Read exactly `length` bytes buf := make([]byte, length) if _, err := io.ReadFull(conn, buf); err != nil { log.Printf("[socket] read frame error: %v", err) break } b.Publish(buf) } conn.Close() log.Printf("[socket] disconnected from %s, reconnecting...", sockPath) time.Sleep(1 * time.Second) } } // --------------------------------------------------------------------------- // HTTP handler — streams MJPEG to browser // --------------------------------------------------------------------------- // listenAddr keeps the stream server off the network. nginx on the same // machine is the only thing that should ever connect to it. const listenAddr = "127.0.0.1:8081" // frameWriteTimeout bounds how long one frame may take to reach a client. // A viewer that stops reading without closing its connection is dropped // after this long instead of holding a goroutine for minutes. const frameWriteTimeout = 5 * time.Second func mjpegHandler(b *Broadcaster) http.HandlerFunc { boundary := "frame" return func(w http.ResponseWriter, r *http.Request) { log.Printf("[http] client connected: %s", r.RemoteAddr) w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary="+boundary) w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") rc := http.NewResponseController(w) ch, latest := b.Subscribe() defer b.Unsubscribe(ch) if latest != nil { if err := writeFrame(rc, w, latest, boundary); err != nil { log.Printf("[http] client disconnected: %s", r.RemoteAddr) return } } for { select { case frame := <-ch: if err := writeFrame(rc, w, frame, boundary); err != nil { log.Printf("[http] client disconnected: %s", r.RemoteAddr) return } case <-r.Context().Done(): log.Printf("[http] client context done: %s", r.RemoteAddr) return } } } } func writeFrame(rc *http.ResponseController, w http.ResponseWriter, frame []byte, boundary string) error { var buf bytes.Buffer buf.WriteString("--" + boundary + "\r\n") buf.WriteString("Content-Type: image/jpeg\r\n\r\n") buf.Write(frame) buf.WriteString("\r\n") if err := rc.SetWriteDeadline(time.Now().Add(frameWriteTimeout)); err != nil { return err } if _, err := w.Write(buf.Bytes()); err != nil { return err } return rc.Flush() } // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- func main() { bc0 := NewBroadcaster() bc1 := NewBroadcaster() go socketReader("/tmp/picam0.sock", bc0) go socketReader("/tmp/picam1.sock", bc1) mux := http.NewServeMux() mux.HandleFunc("/stream/0", mjpegHandler(bc0)) mux.HandleFunc("/stream/1", mjpegHandler(bc1)) mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("ok")) }) // ctx is cancelled on SIGTERM (systemctl stop) or SIGINT (Ctrl+C). ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() srv := &http.Server{ Addr: listenAddr, Handler: mux, ReadHeaderTimeout: 10 * time.Second, // Every request context derives from ctx, so cancelling ctx ends // the streaming loops and lets Shutdown finish. BaseContext: func(net.Listener) context.Context { return ctx }, } go func() { log.Printf("Go MJPEG server listening on %s", listenAddr) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("server error: %v", err) } }() <-ctx.Done() log.Println("shutting down") shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { log.Printf("shutdown: %v", err) } }