diff --git a/cmd/server/main.go b/cmd/server/main.go index 1ad0032..1d0492e 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -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(`

%s

`)) + handler_1, err := handler_client.NewHandler("test", htmxmqtt.PayloadFormatFunc(`

%s

`)) if err != nil { panic(err) } diff --git a/handler.go b/handler.go index ac83a36..e85e0c6 100644 --- a/handler.go +++ b/handler.go @@ -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 {