From 1d7d1f3b1b80ee83bd5b2f6f2776d78b2653b06f Mon Sep 17 00:00:00 2001 From: Helmut Merz Date: Thu, 10 Aug 2023 17:50:11 +0200 Subject: [PATCH] server: provide message processor for fine-tuned handling of remote messages - start with Async() --- server/config.go | 18 ++++++++++++++---- server/server.go | 18 ++++++++++++------ tests/etc/etc.go | 2 +- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/server/config.go b/server/config.go index ca67e5d..095d265 100644 --- a/server/config.go +++ b/server/config.go @@ -41,8 +41,18 @@ func FileServer(docRoot string) *fsSpec { return &fsSpec{docRoot} } -func MsgHandler(pattern string, rcvs ...string) lib.Config { - cfg := config.Base("", nil) - cfg.AddAction(pattern, action.Base(action.Forward, rcvs...)) - return cfg +type mhSpec struct { + lib.Config + proc msgProc } + +func MsgHandler(pattern string, proc msgProc, rcvs ...string) *mhSpec { + if proc == nil { + proc = Async + } + cfg := mhSpec{config.Base("", nil), proc} + cfg.AddAction(pattern, action.Base(action.Forward, rcvs...)) + return &cfg +} + +type msgProc func(lib.Context, lib.Message) (int, Data) diff --git a/server/server.go b/server/server.go index 673fb46..18a6442 100644 --- a/server/server.go +++ b/server/server.go @@ -10,6 +10,8 @@ import ( "github.com/gin-gonic/gin" ) +type Data = map[string]interface{} + type ServerState struct { server *http.Server } @@ -50,21 +52,25 @@ func setRoute(ctx lib.Context, rcfg routeCfg, r *gin.Engine) { switch spec := rcfg.spec.(type) { case *fsSpec: r.Static(rcfg.path, spec.docRoot) - case lib.Config: + case *mhSpec: r.Match(rcfg.methods, rcfg.path+"/*msg", func(c *gin.Context) { - handle(ctx, spec, c) + handleMsg(ctx, spec, c) }) } } // scopes standard request (= message) handler implementation -func handle(ctx lib.Context, cfg lib.Config, gc *gin.Context) { +func handleMsg(ctx lib.Context, cfg *mhSpec, gc *gin.Context) { head := strings.Split(gc.Param("msg"), "/")[1:] cctx := ctx.ChildContext(cfg) msg := message.New(head...).WithSender(cctx) - //fmt.Printf("*** RCell called: msg: %+v, method: %s\n", msg, gc.Request.Method) + // if gc.Request.Method == "POST" && data != "": msg.WithPayload(data) core.HandleMessage(cctx, msg) - // if cfg.sync: wait for response message - gc.String(http.StatusOK, "Hello World") + code, data := cfg.proc(ctx, msg) + gc.JSON(code, data) +} + +func Async(ctx lib.Context, msg lib.Message) (int, Data) { + return http.StatusOK, Data{"status": "OK"} } diff --git a/tests/etc/etc.go b/tests/etc/etc.go index b1d3a86..6084dd6 100644 --- a/tests/etc/etc.go +++ b/tests/etc/etc.go @@ -32,7 +32,7 @@ func Config() lib.Config { Port: ovr("8123", SERVER_PORT), } server_c.AddRoute("/docs", server.FileServer("html")) - server_c.AddRoute("/api", server.MsgHandler("demo", "test-receiver")) + server_c.AddRoute("/api", server.MsgHandler("demo", nil, "test-receiver")) test_client := &client.Cfg{ BaseCfg: b("test-client", core.Start),