knowyt/server/handler/sync.go
2021-07-30 21:49:18 +02:00

38 lines
731 B
Go

package handler
import (
"encoding/json"
"fmt"
"github.com/imkira/go-observer"
"net/http"
"sirlab.de/go/knyt/syncdata"
"strconv"
)
func SyncFactory(obs observer.Property) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
versionRef, err := strconv.Atoi(r.URL.Query().Get("v"))
if err != nil {
versionRef = -1
}
stream := obs.Observe()
var value syncdata.SyncData
for {
value = stream.Value().(syncdata.SyncData)
if value.VersionRef >= versionRef {
break
}
select {
case <-stream.Changes():
stream.Next()
}
}
jsonString, _ := json.MarshalIndent(value, "", " ")
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, string(jsonString))
}
}