builtin-programs/web/camera-slice.folk

When the jpeg library is /jpegLib/ {
    Wish the web server handles route {/camera-slice/([^/]+)$} with handler {
        set id [string map [list %20 " "] $1]
        Hold! -key [list camera-slice $id] Wish $id has camera slice

        set filename "/tmp/web-camera-slice-$id.jpg"
        set found false
        for {set i 0} {$i < 100} {incr i} {
            ForEach! $id has camera slice /slice/ {
                $jpegLib saveAsJpeg $slice $filename
                set found true

                # HACK: there's race risk here
                Hold! -key [list camera-slice $id] {}
                break
            }
            if {$found} { break }
            after 10
        }
        if {!$found} {
            error "camera-slice: Timeout waiting for camera slice for $id"
        }

        set fsize [file size $filename]
        set fd [open $filename r]
        fconfigure $fd -translation binary
        set data [read $fd $fsize]
        close $fd

        dict create statusAndHeaders "HTTP/1.1 200 OK
Connection: close
Content-Type: image/jpeg
Content-Length: $fsize\n\n" \
            body $data
    }
}