knowyt/server/handler/sync.go

38 lines
731 B
Go
Raw Normal View History

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