basic stream saving working

This commit is contained in:
BroodjeAap 2020-06-30 18:40:40 +00:00
parent cde2f0ebf3
commit d6ac177d87

36
main.go
View file

@ -1,9 +1,12 @@
package main
import (
"crypto/sha256"
"encoding/base64"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"text/template"
)
@ -38,7 +41,7 @@ func stream(w http.ResponseWriter, r *http.Request) {
if r.FormValue("URL") == "" {
return
}
//w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Type", "image/jpeg")
URL := r.FormValue("URL")
resp, err := http.Get(URL)
if err != nil {
@ -47,9 +50,40 @@ func stream(w http.ResponseWriter, r *http.Request) {
img, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
// TODO async for this?
saveStreamInstant(URL, img)
w.Write([]byte(img))
}
func saveStreamInstant(URL string, img []byte) {
h := sha256.New()
h.Write([]byte(URL))
streamDir := base64.URLEncoding.EncodeToString(h.Sum(nil))
streamStoreDir := filepath.Join(".", "streams", string(streamDir))
os.MkdirAll(streamStoreDir, os.ModePerm)
currentStreamInstantPath := filepath.Join(streamStoreDir, "current.jpg")
_, err := os.Stat(currentStreamInstantPath)
swap := !os.IsNotExist(err)
if swap {
currentStreamInstantPath = filepath.Join(streamStoreDir, "next.jpg")
}
err = ioutil.WriteFile(currentStreamInstantPath, img, os.ModePerm)
if err != nil {
log.Fatal("Can't write latest stream instant.")
}
if swap {
previousStreamInstantPath := filepath.Join(streamStoreDir, "previous.jpg")
nextStreamInstantPath := currentStreamInstantPath
currentStreamInstantPath = filepath.Join(streamStoreDir, "current.jpg")
err = os.Rename(currentStreamInstantPath, previousStreamInstantPath)
err = os.Rename(nextStreamInstantPath, currentStreamInstantPath)
}
}
func main() {
staticFileServer := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", staticFileServer))