knowyt/server/handler/sync.go

41 lines
733 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"
"strconv"
)
type Value struct {
2021-07-30 18:18:04 +00:00
VersionRef int `json:"version"`
2021-07-29 16:39:12 +00:00
}
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()
var value Value
for {
value = stream.Value().(Value)
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
}
}