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

41 lines
733 B
Go

package handler
import (
"encoding/json"
"fmt"
"github.com/imkira/go-observer"
"net/http"
"strconv"
)
type Value struct {
VersionRef int `json:"version"`
}
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 Value
for {
value = stream.Value().(Value)
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))
}
}