1
0
Fork 0
mirror of https://github.com/Luzifer/cam2mjpeg.git synced 2024-12-21 01:41:18 +00:00

Add handler for single jpeg image

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2019-04-29 11:14:43 +02:00
parent f8201396a2
commit 0a2e1b9a05
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E

26
main.go
View file

@ -10,9 +10,10 @@ import (
"strconv" "strconv"
"sync" "sync"
rconfig "github.com/Luzifer/rconfig/v2"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
rconfig "github.com/Luzifer/rconfig/v2"
) )
var ( var (
@ -46,7 +47,7 @@ func init() {
} }
if cfg.VersionAndExit { if cfg.VersionAndExit {
fmt.Printf("imgdecode %s\n", version) fmt.Printf("cam2mjpeg %s\n", version)
os.Exit(0) os.Exit(0)
} }
@ -59,6 +60,7 @@ func init() {
func main() { func main() {
http.HandleFunc("/mjpeg", handle) http.HandleFunc("/mjpeg", handle)
http.HandleFunc("/snapshot.jpg", handleSnapshot)
go func() { go func() {
log.WithError(http.ListenAndServe(cfg.Listen, nil)).Fatal("HTTP server has gone") log.WithError(http.ListenAndServe(cfg.Listen, nil)).Fatal("HTTP server has gone")
}() }()
@ -146,6 +148,26 @@ func handle(res http.ResponseWriter, r *http.Request) {
handleMJPEG(res, r, imgChan, uid) handleMJPEG(res, r, imgChan, uid)
} }
func handleSnapshot(w http.ResponseWriter, r *http.Request) {
imgChan := make(chan []byte, 10)
uid := uuid.Must(uuid.NewV4()).String()
defer func() {
deregisterImgChan(uid)
close(imgChan)
}()
registerImgChan(uid, imgChan)
img := <-imgChan
w.Header().Add("Cache-Control", "no-store, no-cache")
w.Header().Add("Connection", "close")
w.Header().Set("Content-Type", "image/jpeg")
w.Write(img)
}
func registerImgChan(id string, ic chan []byte) { func registerImgChan(id string, ic chan []byte) {
requesterLock.Lock() requesterLock.Lock()
defer requesterLock.Unlock() defer requesterLock.Unlock()