Moved to slog and fixed cmd/server

master
noah metz 2023-12-30 16:39:30 -07:00
parent 508f42da34
commit 5602f72235
2 changed files with 18 additions and 10 deletions

@ -5,16 +5,19 @@ import (
"errors"
"os/signal"
"syscall"
"net/http"
"os"
"fmt"
)
func main() {
handler_client, err := NewMQTTHandlerClient("tcp://localhost:1883", "", "", "htmx")
handler_client, err := htmxmqtt.NewMQTTHandlerClient("tcp://localhost:1883", "", "", "htmx")
if err != nil {
panic(err)
}
handler_1, err := handler_client.NewHandler("test", PayloadFormatFunc(`<p id="test">%s</p>`))
handler_1, err := handler_client.NewHandler("test", htmxmqtt.PayloadFormatFunc(`<p id="test">%s</p>`))
if err != nil {
panic(err)
}

@ -3,7 +3,7 @@ package htmxmqtt
import (
"time"
"net/http"
"os"
"log/slog"
"fmt"
"context"
"sync"
@ -31,7 +31,7 @@ func (handler *MQTTHandler) processMessage(client mqtt.Client, message mqtt.Mess
case channel <- message:
remaining = append(remaining, channel)
default:
os.Stderr.WriteString("Channel overflow\n")
slog.Warn("Channel overflow")
}
}
@ -107,7 +107,10 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("websocket accept error: %s\n", err))
slog.Error("websocket accept error", "error", err)
return
} else {
slog.Info("new websocket connection", "addr", r.RemoteAddr)
}
defer conn.CloseNow()
@ -117,11 +120,11 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for true {
msg_type, data, err := conn.Read(ctx)
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("websocket error: %s\n", err))
slog.Error("websocket error", "error", err)
cancel_func()
break
} else {
os.Stderr.WriteString(fmt.Sprintf("websocket data(%s): %s\n", msg_type, string(data)))
slog.Debug("websocket data", "type", msg_type, "data", string(data))
}
}
}(conn, cancel_func)
@ -131,18 +134,20 @@ func (handler *MQTTHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for running == true {
select {
case <- done:
os.Stderr.WriteString("websocket context done")
slog.Debug("websocket context done")
running = false
case message := <- channel:
text := handler.format(message)
os.Stderr.WriteString(fmt.Sprintf("websocket write: %s\n", text))
slog.Debug("websocket write", "data", text)
err := conn.Write(ctx, websocket.MessageText, text)
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("websocket write error: %s\n", err))
slog.Error("websocket write error", "error", err)
running = false
}
}
}
slog.Info("closing websocket", "addr", r.RemoteAddr)
}
func PayloadFormatFunc(template string) MQTTFormatFunc {