update communication

This commit is contained in:
Settel 2021-07-28 23:17:08 +02:00
parent 3933bf8585
commit 350f887a45
3 changed files with 61 additions and 1 deletions

View File

@ -1,3 +1,5 @@
module sirlab.de/go/knyc module sirlab.de/go/knyc
go 1.16 go 1.16
require github.com/imkira/go-observer v1.0.3

2
server/go.sum Normal file
View File

@ -0,0 +1,2 @@
github.com/imkira/go-observer v1.0.3 h1:l45TYAEeAB4L2xF6PR2gRLn2NE5tYhudh33MLmC7B80=
github.com/imkira/go-observer v1.0.3/go.mod h1:zLzElv2cGTHufQG17IEILJMPDg32TD85fFgKyFv00wU=

View File

@ -2,22 +2,78 @@ package main
import ( import (
"fmt" "fmt"
"github.com/imkira/go-observer"
"net/http" "net/http"
"sirlab.de/go/knyc/handler" "sirlab.de/go/knyc/handler"
"strconv"
"time"
) )
type Value struct {
value int
}
type Engine struct {
payload observer.Property
}
var engine Engine
func (engine Engine) runEngine() {
for {
value := engine.payload.Value().(Value)
fmt.Printf("sleep: %d\n", value.value)
time.Sleep(1 * time.Second)
value.value++
engine.payload.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)
}
}
func main() { func main() {
app := handler.NewAuthMux() app := handler.NewAuthMux()
http.Handle("/", app) http.Handle("/", app)
app.PublicHandleFunc("/__intern__/exit", handler.Exit) app.PublicHandleFunc("/__intern__/exit", handler.Exit)
payload := observer.NewProperty(Value{value: 19})
sync := syncFactory(payload)
app.PublicHandleFunc("/sync", sync)
// hanlde login page // hanlde login page
fsHandler := http.FileServer(http.Dir("../client/dist/")) fsHandler := http.FileServer(http.Dir("../client/dist/"))
// default handler // default handler
app.PublicHandle("/", fsHandler) app.PublicHandle("/", fsHandler)
engine.payload = payload
go engine.runEngine()
// start listening // start listening
fmt.Println("http://localhost:32039") fmt.Println("http://localhost:32039")
http.ListenAndServe(":32039", nil) http.ListenAndServe(":32039", nil)