moved sync handler to own file

This commit is contained in:
Settel 2021-07-29 18:39:12 +02:00
parent 350f887a45
commit 022fe8d87d
2 changed files with 46 additions and 40 deletions

38
server/handler/sync.go Normal file
View File

@ -0,0 +1,38 @@
package handler
import (
"fmt"
"github.com/imkira/go-observer"
"net/http"
"strconv"
)
type Value struct {
Value int
}
func SyncFactory(obs observer.Property) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
refId, err := strconv.Atoi(r.URL.Query().Get("ref"))
if err != nil {
refId = -1
}
stream := obs.Observe()
var value Value
for {
value = stream.Value().(Value)
if value.Value > refId {
break
}
select {
case <-stream.Changes():
stream.Next()
}
}
w.Header().Add("Content-Type", "text/plain")
fmt.Fprintf(w, "%d (%d)\n", value.Value, refId)
}
}

View File

@ -5,53 +5,22 @@ import (
"github.com/imkira/go-observer" "github.com/imkira/go-observer"
"net/http" "net/http"
"sirlab.de/go/knyc/handler" "sirlab.de/go/knyc/handler"
"strconv"
"time" "time"
) )
type Value struct {
value int
}
type Engine struct { type Engine struct {
payload observer.Property obs observer.Property
} }
var engine Engine var engine Engine
func (engine Engine) runEngine() { func (engine Engine) runEngine() {
for { for {
value := engine.payload.Value().(Value) value := engine.obs.Value().(handler.Value)
fmt.Printf("sleep: %d\n", value.value) fmt.Printf("sleep: %d\n", value.Value)
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
value.value++ value.Value++
engine.payload.Update(value) engine.obs.Update(value)
}
}
func syncFactory(payload observer.Property) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
refId, err := strconv.Atoi(r.URL.Query().Get("ref"))
if err != nil {
refId = -1
}
stream := payload.Observe()
var value Value
for {
value = stream.Value().(Value)
if value.value > refId {
break
}
select {
case <-stream.Changes():
stream.Next()
}
}
w.Header().Add("Content-Type", "text/plain")
fmt.Fprintf(w, "%d (%d)\n", value.value, refId)
} }
} }
@ -61,9 +30,8 @@ func main() {
app.PublicHandleFunc("/__intern__/exit", handler.Exit) app.PublicHandleFunc("/__intern__/exit", handler.Exit)
payload := observer.NewProperty(Value{value: 19}) obs := observer.NewProperty(handler.Value{Value: 19})
sync := syncFactory(payload) app.PublicHandleFunc("/sync", handler.SyncFactory(obs))
app.PublicHandleFunc("/sync", sync)
// hanlde login page // hanlde login page
fsHandler := http.FileServer(http.Dir("../client/dist/")) fsHandler := http.FileServer(http.Dir("../client/dist/"))
@ -71,7 +39,7 @@ func main() {
// default handler // default handler
app.PublicHandle("/", fsHandler) app.PublicHandle("/", fsHandler)
engine.payload = payload engine.obs = obs
go engine.runEngine() go engine.runEngine()
// start listening // start listening