package main
import (
"html"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func push(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade failed: ", err)
return
}
defer conn.Close()
for {
message := []byte(html.EscapeString("<p>PLEASE</p>"))
conn.WriteMessage(websocket.TextMessage, message)
if err != nil {
log.Println("write failure ", err)
break
}
}
}
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.HandleFunc("/board", push)
http.ListenAndServe(":80", nil)
}
#gorilla/websockets with a side of htmx/ws - How am i supposed to debug this?
13 messages · Page 1 of 1 (latest)
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]" integrity="sha384-FhXw7b6AlE/jyjlZH5iHa/tTe9EpJ1Y55RjcgPbjeWMskSxZt1v9qkxLJWNJaGni" crossorigin="anonymous"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script>
</head>
<body>
<p hx-ext="ws" hx-swap="outerHTML" ws-connect="/board" id="hihi">Hello!</p>
</body>
</html>
The top code block is my webserver
The second is my simple static page for testing
i simply want to be able to push html from the server and have it replace content in the dom but have just gotten nothing
I have no clue whether this issue lies in my implementation of the webserver or in the static page
The docs are a little vague, but I think you need matching id props on the p elements: https://htmx.org/extensions/web-sockets/#receiving-messages-from-a-websocket
yeah i've managed to get some actual output
package main
import (
"html/template"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func push(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade failed: ", err)
return
}
defer conn.Close()
for {
time.Sleep(time.Second)
s := "<p id=\"thething\"> {{.}} </p>"
tmpl := template.Must(template.New("test").Parse(s))
writer, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Println("write failure ", err)
break
}
currenttime := time.Now().Format("03:04:05 PM")
tmpl.Execute(writer, currenttime)
writer.Close()
}
}
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.HandleFunc("/board", push)
http.ListenAndServe(":80", nil)
}
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]" integrity="sha384-FhXw7b6AlE/jyjlZH5iHa/tTe9EpJ1Y55RjcgPbjeWMskSxZt1v9qkxLJWNJaGni" crossorigin="anonymous"></script>
<script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script>
</head>
<body>
<div hx-ext="ws" ws-connect="/board">
<p id="thething">hi</p>
</div>
</body>
</html>
structure looks like this now
and it works
was only a massive struggle