refactoring

This commit is contained in:
Settel 2021-07-29 21:06:25 +02:00
parent f14d47f34a
commit f4bd361e8e
5 changed files with 45 additions and 33 deletions

33
server/engine/engine.go Normal file
View File

@ -0,0 +1,33 @@
package engine
import (
"fmt"
"github.com/imkira/go-observer"
"sirlab.de/go/knyc/handler"
"time"
)
type Engine struct {
obs observer.Property
}
func NewEngine() *Engine {
engine := Engine{
obs: observer.NewProperty(handler.Value{}),
}
return &engine
}
func (engine *Engine) Run() {
for {
value := engine.obs.Value().(handler.Value)
fmt.Printf("sleep: %d\n", value.Value)
time.Sleep(1 * time.Second)
value.Value++
engine.obs.Update(value)
}
}
func (engine *Engine) GetHttpHandler() handler.HandlerFunc {
return handler.SyncFactory(engine.obs)
}

View File

@ -4,6 +4,8 @@ import (
"net/http"
)
type HandlerFunc func(http.ResponseWriter, *http.Request)
type AuthMux struct {
mux *http.ServeMux
}
@ -18,7 +20,7 @@ func (authMux *AuthMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
authMux.mux.ServeHTTP(w, r)
}
func (authMux *AuthMux) PublicHandleFunc(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
func (authMux *AuthMux) PublicHandleFunc(pattern string, handlerFunc HandlerFunc) {
authMux.mux.HandleFunc(pattern, handlerFunc)
}

View File

@ -7,13 +7,11 @@ import (
"time"
)
type HttpHandler func(http.ResponseWriter, *http.Request)
func Exit(_ http.ResponseWriter, _ *http.Request) {
os.Exit(0)
}
func CreateVersionHandler() HttpHandler {
func CreateVersionHandler() HandlerFunc {
startTime := time.Now().Unix()
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%d\n", startTime)

View File

@ -11,7 +11,7 @@ type Value struct {
Value int
}
func SyncFactory(obs observer.Property) HttpHandler {
func SyncFactory(obs observer.Property) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
refId, err := strconv.Atoi(r.URL.Query().Get("ref"))
if err != nil {

View File

@ -2,45 +2,24 @@ package main
import (
"fmt"
"github.com/imkira/go-observer"
"net/http"
"sirlab.de/go/knyc/engine"
"sirlab.de/go/knyc/handler"
"time"
)
type Engine struct {
obs observer.Property
}
var engine Engine
func (engine Engine) runEngine() {
for {
value := engine.obs.Value().(handler.Value)
fmt.Printf("sleep: %d\n", value.Value)
time.Sleep(1 * time.Second)
value.Value++
engine.obs.Update(value)
}
}
func main() {
app := handler.NewAuthMux()
http.Handle("/", app)
app.PublicHandleFunc("/__intern__/exit", handler.Exit)
obs := observer.NewProperty(handler.Value{Value: 19})
app.PublicHandleFunc("/sync", handler.SyncFactory(obs))
// hanlde login page
fsHandler := http.FileServer(http.Dir("../client/dist/"))
// default handler
fsHandler := http.FileServer(http.Dir("../client/dist/"))
app.PublicHandle("/", fsHandler)
engine.obs = obs
go engine.runEngine()
eng := engine.NewEngine()
app.PublicHandleFunc("/sync", eng.GetHttpHandler())
go eng.Run()
// start listening
fmt.Println("http://localhost:32039")