From 47c93e5141ac438fb6a893b2d558e7a83053d5a8 Mon Sep 17 00:00:00 2001 From: Noah Metz Date: Sat, 30 Dec 2023 16:21:46 -0700 Subject: [PATCH] Fixed HTML and made format a function instead of template string --- main.go | 24 ++++++++++++++---------- site/index.html | 8 ++++---- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/main.go b/main.go index fda972d..4353160 100644 --- a/main.go +++ b/main.go @@ -16,9 +16,10 @@ import ( mqtt "github.com/eclipse/paho.mqtt.golang" ) +type MQTTFormatFunc func(mqtt.Message) []byte type MQTTHandler struct { sync.Mutex - Template string + Format MQTTFormatFunc Channels []chan mqtt.Message } @@ -87,9 +88,9 @@ func NewMQTTHandlerClient(broker string, username string, password string, id st }, nil } -func (client *MQTTHandlerClient) NewHandler(subscription string, template string) (*MQTTHandler, error) { +func (client *MQTTHandlerClient) NewHandler(subscription string, format MQTTFormatFunc) (*MQTTHandler, error) { handler := &MQTTHandler{ - Template: template, + Format: format, } sub_token := client.Subscribe(subscription, 0x00, handler.ProcessMessage) @@ -103,10 +104,6 @@ func (client *MQTTHandlerClient) NewHandler(subscription string, template string return handler, nil } -func (handler *MQTTHandler) Format(message mqtt.Message) []byte { - return []byte(fmt.Sprintf(handler.Template, message.Payload())) -} - func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { channel := make(chan mqtt.Message, 1) remove_channel := handler.AddChannel(channel) @@ -141,8 +138,9 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { os.Stderr.WriteString("websocket context done") running = false case message := <- channel: - os.Stderr.WriteString(fmt.Sprintf("websocket write: %s\n", message.Payload())) - err := conn.Write(ctx, websocket.MessageText, message.Payload()) + text := handler.Format(message) + os.Stderr.WriteString(fmt.Sprintf("websocket write: %s\n", text)) + err := conn.Write(ctx, websocket.MessageText, text) if err != nil { os.Stderr.WriteString(fmt.Sprintf("websocket write error: %s\n", err)) running = false @@ -151,13 +149,19 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +func PayloadFormatFunc(template string) MQTTFormatFunc { + return func(message mqtt.Message) []byte { + return []byte(fmt.Sprintf(template, message.Payload())) + } +} + func main() { handler_client, err := NewMQTTHandlerClient("tcp://localhost:1883", "", "", "htmx") if err != nil { panic(err) } - handler_1, err := handler_client.NewHandler("test", "%s") + handler_1, err := handler_client.NewHandler("test", PayloadFormatFunc(`

%s

`)) if err != nil { panic(err) } diff --git a/site/index.html b/site/index.html index f6a7377..9213104 100644 --- a/site/index.html +++ b/site/index.html @@ -1,4 +1,4 @@ - + HTMX MQTT Test Page @@ -11,10 +11,10 @@

Test Page

- - + +
-
+