server: Sync message processor (work in progress)

This commit is contained in:
Helmut Merz 2023-08-13 22:24:43 +02:00
parent ec1ab12cef
commit 049998d5ec
4 changed files with 19 additions and 6 deletions

View file

@ -116,11 +116,11 @@ func (pl *payload) FromJson(s string) lib.Payload {
return pl return pl
} }
func Payload(d interface{}) lib.Payload { func Payload(d lib.Data) lib.Payload {
return &payload{d} return &payload{d}
} }
func PayloadFromJson[T any](s string) lib.Payload { func PayloadFromJson[T lib.Data](s string) lib.Payload {
pl := &payload{new(T)} pl := &payload{new(T)}
return pl.FromJson(s) return pl.FromJson(s)
} }

View file

@ -51,7 +51,8 @@ func MsgHandler(pattern string, proc msgProc, rcvs ...string) *mhSpec {
if proc == nil { if proc == nil {
proc = Async proc = Async
} }
cfg := mhSpec{config.Base("", nil), proc} //cfg := mhSpec{config.Dummy(), proc}
cfg := mhSpec{config.Default(""), proc}
cfg.AddAction(pattern, action.Base(action.Forward, rcvs...)) cfg.AddAction(pattern, action.Base(action.Forward, rcvs...))
return &cfg return &cfg
} }

View file

@ -3,6 +3,7 @@ package server
import ( import (
"net/http" "net/http"
"strings" "strings"
"time"
lib "git.sr.ht/~cco/go-scopes" lib "git.sr.ht/~cco/go-scopes"
"git.sr.ht/~cco/go-scopes/config" "git.sr.ht/~cco/go-scopes/config"
@ -78,10 +79,21 @@ func Async(ctx lib.Context, msg lib.Message) (int, lib.Data) {
return http.StatusOK, lib.Map{"status": "OK"} return http.StatusOK, lib.Map{"status": "OK"}
} }
func Sync(ctx lib.Context, msg lib.Message) (int, lib.Data) { func Sync(timeout int) msgProc {
return func(ctx lib.Context, msg lib.Message) (int, lib.Data) {
return sync(ctx, msg, timeout)
}
}
func sync(ctx lib.Context, msg lib.Message, to int) (int, lib.Data) {
timeout := time.Duration(to) * time.Second
select { select {
case msg := <-ctx.Mailbox(): case msg := <-ctx.Mailbox():
return http.StatusOK, msg.Payload().Data() return http.StatusOK, msg.Payload().Data()
case <-time.After(timeout):
return http.StatusNoContent, nil
case <-ctx.Done():
return http.StatusGone, nil
} }
return http.StatusOK, lib.Map{"status": "OK"} return http.StatusNoContent, nil
} }

View file

@ -29,7 +29,7 @@ func Config() lib.Config {
server_c := b("server", server.Start( server_c := b("server", server.Start(
(&server.Cfg{Port: ovr("8123", SERVER_PORT)}). (&server.Cfg{Port: ovr("8123", SERVER_PORT)}).
AddRoute("/docs", server.FileServer("html")). AddRoute("/docs", server.FileServer("html")).
AddRoute("/api", server.MsgHandler("demo", nil, "test-receiver")), AddRoute("/api", server.MsgHandler("demo", server.Async, "test-receiver")),
)) ))
test_client := &client.Cfg{ test_client := &client.Cfg{